首页 > 解决方案 > Dao 类的单一职责原则

问题描述

这是一个没有遵循单一职责原则的示例代码,

public class EmailSender
{
  public void SendEmail(string customerID, 
                       string emailNotificationType)
  {
    //STEP1: load customer details
    //STEP2: get email content
    //STEP3: send email (using SmtpClient class)
  }

  public string GetEmailContent(Customer customer, 
                 string emailNotificationType)
   {
    // Build the email notification content
   }
}

我同意,如果我需要执行以下操作,它会产生问题,

-> Changes in the way, you are loading customer details.

-> Changes to the email content because of requirement enhancements / changes.

-> If there any change in the way you are sending the email instead of using SmtpClient class or something like that.

所以我们需要应用单一责任原则来分离类。我完全同意这个原则。说我需要创建三个类

EmailSender - 只专注于发送电子邮件 CustomerRepository - 只专注于获取客户数据 EmailContentBuilder - 解析电子邮件内容

但是说如果我有一个像 CustomerDao 这样的 Dao,到目前为止,我在同一个类中拥有与 CustomerDao 相关的所有 CRUD 操作,如下所示

CustomerDao 类
- add()
- update() - get()
- getAll()
- update()

我们需要在这里应用 SingleResponsibilityPrinciple 吗?如果是这样如何申请CustomerDao类?

谢谢,
哈利

标签: javadesign-patternssolid-principlessingle-responsibility-principle

解决方案


你不想申请 DAO,因为它只做一件事。

好的例子

模式和原则是很棒的东西,但是如果使用不当,它们会使一个简单的问题变得像没有它们一样复杂。

不应以严格的方式理解 SRP。一个对象应该有很少的职责,而不是“一个”。这里CustomerDao 只负责Customer 持久化,所以它只有一个职责。


推荐阅读