我是面向对象编程的新手。我想根据从 UI 请求中收到的 EnumType 创建电子邮件正文。
例如,如果我收到枚举值 A,我需要构建一个电子邮件正文,其中包含从数据库和其他服务收到的一些属性。 如果枚举值不同,我需要不同的行为。
我尝试创建
public interface EmailService {
String getBody();
String getStatus();
}
public class AEmailService implements EmailService {
Service X;
DAOService Y;
.... Some operations.
}
public class BEmailService implements EmailService {
Service X;
DAOService Y;
.... Some operations.
}
现在,我如何使用 EmailService 接口(interface)并根据请求中的枚举值在运行时将其替换为 AEmailService 或 BEmailService 的对象。
执行此操作是否更好?
最佳答案
您可以参数化您的 enum
与 Supplier<EmailService>
,例如:
public enum EmailServiceTypes {
A(AEmailService::new),
B(BEmailService::new);//etc
private Supplier<EmailService> supplier;
EmailServiceTypes(Supplier<EmailService> supplier) {
this.supplier = supplier;
}
public EmailService supply() {
return supplier.get();
}
}
根据您作为输入获得的枚举值,您只需调用 get
您将获得所需的实例。
关于java - Java 中的多态性与服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56583216/