【发布时间】:2015-08-08 12:41:58
【问题描述】:
我有一个关于 OOD、OOP 和建模的一般性问题,但我不知道如何提问。最简单的方法是举例。我通常使用 PHP,但它可以是任何其他语言。假设我是一家银行,我想制作一个处理提款的程序。因此,我将进行 2 类取款和帐户。现在有什么更好的功能,使退出。 我的意思是:
$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);
也许所有选项都同样可行?
【问题讨论】:
-
这个问题太笼统了。诸如“您认为哪种方式最好”之类的设计问题并不是真正可以回答的,因为这将是意见。 “最佳”取决于您未指定的许多其他功能:您还必须支持哪些其他功能?这些类会在另一个应用程序中重用吗?
标签: php oop design-patterns modeling