【发布时间】:2019-06-25 04:07:51
【问题描述】:
这是一个没有遵循单一职责原则的示例代码,
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 类
- 添加()
- 更新()
- 获取()
- getAll()
- 更新()
我们需要在这里应用 SingleResponsibilityPrinciple 吗?如果是这样如何申请CustomerDao类?
谢谢,
哈利
【问题讨论】:
-
我相信Software Engineering Stack Exchange 可能更适合您的问题。
-
@abra,恕我直言,我相信这也是一个程序性问题,请让我知道您对 CustomerDao 的看法
-
检查这个,在正确的抽象级别应用模式很重要。 softwareengineering.stackexchange.com/questions/155627/…
-
CRUD如果在单节课中使用很好,是的,你做得很好。除非您准备好为小型操作维护该级别的代码库,否则不要将太多责任委托给其他类。而mail Sender可以是静态的,可以用作util类:)
标签: java design-patterns solid-principles single-responsibility-principle