is modifying singleton class codes the only way to extend the functionality of the singleton when using enum version singleton pattern?

时间:2019-04-17 01:51:30

标签: java design-patterns enums singleton

Recently, when I ask how to make methods thread-safe in singleton pattern, someone told me that using an enum version singleton pattern is a good option. and by multiple threads. If the method has side effects (changes the state of some variable) then you need to think about protecting it (make it synchronized) or parts thereof. So I write code like this:

public enum ReStation {
    INSTANCE;  

    private List<Email> emailList;

    private ReStation() {
        emailList = new ArrayList<>();
    }

    public synchronized void recycleEmail(Email email) {
        System.out.println("Recycle station recycleing the email: "
                        + email.getContent());
        emailList.add(email);
    }

    public synchronized void deleteEmail(Email email) {
        emailList.remove(email);
    }

    public synchronized void clear() {
        emailList.clear();
    }
}

however, when I read the book named "Design Pattern-Elements of Reusable Object-Oriented Software", I come across such a paragraph as below :

Applicability
Use the Singleton pattern when
• there must be exactly one instance of a class, and it must be accessible to clients from a well-known access point.
• when the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code.

Given an enum can't be extended, I am really confused about How could I use an extended instance without modifying their code while using an enum version singleton pattern? is modifying singleton class codes the only way to extend the functionality of the singleton?

1 个答案:

答案 0 :(得分:1)

当引号中说“唯一的实例应该可以通过子类扩展”时,他们正在谈论以下情况:

  • 您需要基类或接口的单个可分辨实例,该实例具有众所周知的访问点,例如进程Logger;

  • 您需要在运行时选择具体的实现,例如基于配置或其他运行时信息。例如,您的流程Logger可以由FileLoggerConsoleLogger实现。通常,应该可以使用任何Logger子类来实现系统记录器。

您不能使用“枚举版本单例模式”来完成此操作。