【问题标题】:Can Singleton Pattern work for more than one (but fixed) number of instances单例模式能否适用于多个(但固定)数量的实例
【发布时间】:2014-02-23 09:07:39
【问题描述】:

我遇到了一个关于设计模式的问题。

它要求在一个类的两个实例被创建的场景中使用 apt 设计模式。我不确定答案,但后来的描述说 Singleton 可以用于这种情况。它说 Singleton 可以确保只创建一个类的一个实例或一个固定数量的实例(不是一个)。

我一直将单例模式理解为一种模式,其中只能创建一个类的一个对象,因此这个解释让我感到惊讶。我不确定我是否同意。

有什么想法吗?

阿迪亚

【问题讨论】:

  • 我认为你想要的是一个 pool,其中有固定数量的对象,你可以得到一个,然后将其释放回池中。这通常通过线程池中的线程来完成。
  • 当然你可以实现类似的东西,但我不会再称之为“单例模式”了。
  • 实际上并不相关,但单例作为一种设计模式长期以来一直被认为是一种反实践。如果你想使用真正的单例,你应该使用 @Singleton 注释或类似的依赖注入

标签: design-patterns singleton


【解决方案1】:

下面是一个例子,展示了一个 Multiton 类,它恰好包含 n 个对象:

public class Multiton
{
  private static Multiton[] instances;

  private Multiton() {}

  public static void initializeWithNumberOfInstances(int number)
  {
    instances = new Multiton[number];
  }

  public static Multiton getInstanceAtIndex(int index) throws Exception
  {
    if (instances == null)
      throw new Exception("Initialize number of instances first");

    if (instances[index] == null)
    {
      instances[index] = new Multiton();
    }

    return instances[index];
  }
}

【讨论】:

    【解决方案2】:

    单例设计模式解决了所有这些问题。使用单例设计模式,您可以:

    1.确保只创建一个类的一个实例
    2.提供对象的全局访问点
    3.在不影响单例类的客户端的情况下允许未来的多个实例

    正如上面所说,您只能创建一个类实例并在任何地方使用它。如果我们这样认为,我们实际上也可以创建两个实例。

    class Singleton
    {
         private static Singleton instance1 = null;
         private static Singleton instance2 = null;
         private Singleton{}
         public static Singleton getInstance()
         {
    
             if(instance1 == null)
             {
                   instance1 = new Singleton();
                   return instance1;
             }
             else if(instance2 == null)
             {
                   instance2 = new Singleton();
                   return instance2;
             }
             return instance1;
         }
    }
    

    如果你想创建超过 2 个,那么你可以在 getInstance 中创建,但最好创建一个类数组。

    【讨论】:

      【解决方案3】:

      multiton 在管理有限池(例如线程、连接)以及控制/限制producer-consumer 模式中的消费者数量方面具有常见应用,例如here。也可以使用术语“单例注册表”,尽管这可能是指在DictionaryHashMap 中键入实例的常见实现,而不是设计概念。

      根据@Stefano 的评论,管理实例的原始GOF 单例implementation of using statics 应替换为外部管理机制,例如IoC 容器controlling the creation and lifespan of instances

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-21
        • 1970-01-01
        • 1970-01-01
        • 2012-09-05
        • 1970-01-01
        • 2017-09-12
        相关资源
        最近更新 更多