java - Java 中的多态性与服务

标签 java oop design-patterns

我是面向对象编程的新手。我想根据从 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 的对象。

执行此操作是否更好?

最佳答案

您可以参数化您的 enumSupplier<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/

相关文章:

java - 异常执行数据流,为什么抛出异常时我的对象为null?

java - 如何在 fx :include? 中指定资源

c++ - getter 和 setter 风格

design-patterns - 创建应用程序/产品配置的设计模式/指南

C++:字段的类型不完整

java - 在这个程序(Java)中,我试图制作一个掷骰子。我怎样才能让它滚动很多次并添加面包卷?

java - 更改 Java printf 中的默认填充字符?

java - 如何通过构造函数中的依赖注入(inject)而不使用框架来应用记录器

java - 导入和更新操作的设计模式

database - 数据库表的草稿版本