solid-principles - 用策略模式重构,然后应用 SOLID 原则

标签 solid-principles strategy-pattern

我在应用程序中有一个如下所示的 C# 类,并正在寻找重构它的方法。

  • 类中不存在 Send 方法。这是我想出的解决方案。
  • future 将会有更多电子邮件类型。
  • 我不知道是否可以在这里应用 SOLID Open/Closed 原则,因为添加新的电子邮件类型需要修改此类。
  • 此服务的使用者不应关心业务逻辑,而只需了解新的 emailTypecustomerIdEmailService 的使用者只知道要发送的电子邮件类型和 customerId

class EmailService
{
    Send(int emailType, int customerId)
    {
        switch(emailType)
        {
            case 1: SendSignupEmail(customerId);
                break;
            case 2: SendOrderEmail(customerId);
                break;
            case 3: SendCancellationEmail(customerId);
                break;
        }
    }

    SendSignupEmail(int customerId);
    SendOrderEmail(int customerId);
    SendCancellationEmail(int customerId);
}

最佳答案

策略模式要求您封装行为,以使您的类保持原子性并为单一目的而设计。

你应该做的是(我会用Java编写它,但在C#中必须非常相似):

interface Message {
    void send(int customerId);
}

class SignupMessage implements Message {
    // here you implement send method with specifics of signup behavior
}
class OrderMessage implements Message {
    // here you implement send method with order specifics
}
class CancellationMessage implements Message {
    // here you implement send method with cancellation specifics
}

class EmailService
{
    void send(Message message, int customerId) {
        message.send(customerId);
    }
}

也有人认为发送逻辑(连接到 POP 服务器并发送邮件)与消息本身无关。保持通用的代码不应该被重新实现,所以我认为这个版本更有意义:

interface Message {
    void getMessage(int customerId);
    // I've assumed only messages are different between message types
}

// other classes are the same as above (only implementing "getMessage" this time)

class EmailService {
    void send(Message message, int customerId) {
        string msg = message->getMessage(customerId);
        // what follows next is logic to send bessage
    }
}

关于solid-principles - 用策略模式重构,然后应用 SOLID 原则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42597134/

相关文章:

java - 如何设计不在/排除查询行为

java - 哪种设计模式可以制作pdf、excel等格式的报告

c++ - 使用策略模式改变方法及其关联状态

oop - 单一责任原则有什么用?

c# - 了解使用单一职责原则的实际好处

java - 为什么不可变对象(immutable对象)允许遵守里氏替换原则?

c# - 实现策略模式。我每次都必须 'new up' 吗?

java - 使用 java 8 和服务注入(inject)的策略模式

基于XSD值的Java SAX策略模式

oop - 覆盖没有 LSP 中断的虚拟 bool 纯方法