使用枚举版本单例模式时,修改单例 class 代码是扩展单例功能的唯一方法吗?

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

最近,当我询问时,有人告诉我使用枚举版本单例模式是一个不错的选择。并通过多个线程。如果该方法有副作用(更改某些变量的状态),那么您需要考虑保护它(使其同步)或其部分。所以我写了这样的代码:

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();
    }
}

然而,当我阅读名为"Design Pattern-Elements of Reusable Object-Oriented Software"的书时,我看到了如下一段话:

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.

鉴于无法扩展枚举,我真的很困惑如何在使用枚举版本单例模式时使用扩展实例而不修改其代码?修改单例 class 代码是扩展单例功能的唯一方法吗?

当引用说 "sole instance should be extensible by subclassing" 时,他们谈论的是以下情况:

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

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

您不能使用 "enum version singleton pattern" 执行此操作。