我在应用程序中有一个如下所示的 C# 类,并正在寻找重构它的方法。
- 类中不存在
Send
方法。这是我想出的解决方案。 - future 将会有更多电子邮件类型。
- 我不知道是否可以在这里应用 SOLID Open/Closed 原则,因为添加新的电子邮件类型需要修改此类。
- 此服务的使用者不应关心业务逻辑,而只需了解新的
emailType
和customerId
。EmailService
的使用者只知道要发送的电子邮件类型和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/