我有一个关于OOD、OOP和建模的一般性问题,但我不确定该如何提问。最简单的方法就是举例。我通常使用PHP,但它可以用任何其他语言。假设我是一家银行,我想编写一个处理提款的程序。所以我会做两个班级的提款和帐目。现在,更好的方法是使用进行取款的函数。我的意思是:
$account = getAccountById(1); //account->balance = 200.00
$withdrawal = new Withdrawal(50,'USD');
$withdrawal->setAccount($account); // $withdrawal->account_id=1
$withdrawal->make(); //SQL changes account where id=1 and set balance to 150
//Also save a row in withdrawal tables with withdraw details或
$account = getAccountById(1); //account->balance = 200.00
$withdrawal = new Withdrawal(50,'USD');
$account->processesWithdraw($withdrawal); //SQL changes account where id=1 and set balance to 150
//Also save a row in withdrawal tables with withdraw
//$withdrawal->account_id=1有一件事是知道的,一个帐户比取款更“重要”,没有它也可以“生活”。也可能有存款或其他操作。
可能还有许多其他方法来完成此操作。你认为哪种方式最好?
我将尝试给出一个更简单的大学网站的例子,它需要允许学生注册课程。
那么当用户点击注册按钮时,你会选择哪一个呢?这一点:
$student = new Student('John Smith');
$course = new Course('Math');
$student->enrollToCourse($course);或者这样:
$student = new Student('John Smith');
$course = new Course('Math');
$course->addStudent($student);或者可能是第三种选择:
$student = new Student('John Smith');
$course = new Course('Math');
EnrollmentService::enrollStudentToCourse($student,$course);也许所有的选择都是同样可行的?
发布于 2015-05-27 01:50:52
更有可能是
$withdrawal = $account->withdraw(50, 'USD');
$withdrawal->completeTransaction();或
$transfer = $account->transfer(50, 'USD', $transferToAccount);
$transfer->completeTransaction();帐户操作应导致交易..事务应该知道如何保持自身,或者在所有更新都不成功时如何回滚
发布于 2015-05-27 02:25:14
对我来说,在OOP中,关键点是清晰。我会这样做。
$account = new Account(1);
$withdrawal = new Withdrawal($account, 50,'USD');
$withdrawal -> makeTransaction();或
$account = new Account(1);
$withdrawal = new Withdrawal($account);
$withdrawal ->setAmmount(50);
$withdrawal ->setCurrency('USD');
$withdrawal -> makeTransaction();我知道这很长,但是这个方法将帮助你遵循“单一责任原则”。
https://stackoverflow.com/questions/30465355
复制相似问题