【问题标题】:Which class should depend on which class based on level of importance哪个类应该取决于基于重要性级别的哪个类
【发布时间】: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


【解决方案1】:

更有可能是

$withdrawal = $account->withdraw(50, 'USD');
$withdrawal->completeTransaction();

$transfer = $account->transfer(50, 'USD', $transferToAccount);
$transfer->completeTransaction();

帐户操作应该导致事务.. 事务应该知道如何自我持久化,或者如果所有更新都不成功则回滚

【讨论】:

  • 那么你是说账户必须创建提现并且实际上有一个用于提现交易的工厂方法?
  • 嗯,在会计系统中,每笔交易通常有两个条目,一个借方和一个贷方。这对我来说意味着有一种叫做交易的东西,它是用两个账户创建的,一个用于借方,一个用于贷方。实际上,没有存款(借方和贷方)就没有提款。取款只是从支票账户转移到存款人责任账户......当存款时......相反......
【解决方案2】:

对我来说,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();

我知道这很长,但这种方法将帮助您遵循“单一责任原则”

【讨论】:

  • 那$account->makeTransaction($withdrawal);而不是 $withdrawal -> makeTransaction();会违反“单一责任原则”吗?
  • $withdrawal 执行实际事务,我想说这是 Active Record 的一个示例。恕我直言,您应该看看 Data Mapper 模式;应该有某种形式的 repository 执行交易,取款是实体(如存款)或价值对象的示例。
  • 好吧,$withdrawal 应该继承自 Operations,makeTransaction 应该在 Operations 中定义,并在 Withdrawal、Deposit 等类中实现,在这种情况下,您将拥有更大的灵活性
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多