java - 创建一个返回单例的工厂

标签 java design-patterns singleton factory

我有公共(public)代码(我称之为 Controller 的多个类)需要由项目中的多个包共享。 我正在考虑创建一个工厂,返回这些 Controller 。 因此,工厂将有一个 HashMap ,它可以返回请求的 Controller 或创建一个新 Controller (如果未创建)。 Controller 有共同的代码,因为我不需要创建这些 Controller 的多个实例,我认为它们应该是单例的。

这看起来是个好方法吗?

最佳答案

我想你需要的是 Multiton pattern .

The multiton pattern is a design pattern similar to the singleton, which allows only one instance of a class to be created. The multiton pattern expands on the singleton concept to manage a map of named instances as key-value pairs. Rather than have a single instance per application (e.g. the java.lang.Runtime object in the Java programming language) the multiton pattern instead ensures a single instance per key.

public class FooMultiton {
    private static final Map<Object, FooMultiton> instances = new HashMap<Object, FooMultiton>();

    private FooMultiton() {
        // no explicit implementation
    }

    public static synchronized FooMultiton getInstance(Object key) {

        // Our "per key" singleton
        FooMultiton instance = instances.get(key);

        if (instance == null) {
            // Lazily create instance
            instance = new FooMultiton();

            // Add it to map   
            instances.put(key, instance);
        }

        return instance;
    }

    // other fields and methods ...
}

The controllers have common code and since I don't need to create multiple instances of these controller, I think they should be singletons.

您需要单个实例不一定意味着您需要一个单例模式。您可以拥有一个实例并将其传递给后续调用。不必使用 private 构造函数强制执行单例。

另请阅读 Evil Singletons有关 Singletons 缺点的更多信息。读完之后,如果您仍然觉得需要 Singleton,那就继续吧。

关于java - 创建一个返回单例的工厂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20471282/

相关文章:

java - 将 Observable<Single<Object>> 转换为 Single<List<Object>>

C++类继承设计选择

java - 如果您已经知道树结构怎么办?复合模式有替代方案吗?

java - 更多 Swing 设计和 Action

android - 在 Android 中保持服务器连接

java - Eclipse中哪里有好的Xj3D教程?

java - 尝试在Java中使用xlsx读取并返回字符串数组

java - 单例比静态好?

ios - 将 KVC 与单例模式结合使用

java - java中删除标点符号