【问题标题】:Limit the number of DIRECT Instances of a class限制类的 DIRECT 实例数
【发布时间】:2011-11-10 16:29:07
【问题描述】:

换句话说:一个类如何跟踪它的构造函数是由于实例化它的子类还是它的实例是直接创建的?

[请参考以下示例代码]:

class Parent
{
    .............
    .........
    ..............
}

class Child1 extends Parent
{
    .............
    .........
    ..............
}

class Child2 extends Parent
{
    .............
    .........
    ..............
}

我想限制通过调用new Parent(...) 创建的Parent 类的直接实例的数量,并且从计数中排除由于实例化任何子类Child1 或@ 而创建的Parent 实例的数量987654326@.

【问题讨论】:

  • 什么是“子类”?你的意思是内部类?你能提供一些这个案例的示例代码吗?
  • @DmitryBeransky,我已经编辑了我的问题,为什么会有反对票?

标签: java inheritance constructor instantiation


【解决方案1】:

你可以的

static final AtomicInteger count = new AtomicInteger();

// in your Parent constructor.
if (getClass() == Parent.class && count.incrementAndGet() >= LIMIT)
   throw new IllegalStateException();

您能解释一下为什么要这样做吗?当达到限制时,您希望发生什么?

【讨论】:

  • 谢谢,这行得通,当然我有我自己的异常,当不同类达到限制时会抛出,谢谢指导
【解决方案2】:

如果您愿意遵循它,单一职责原则会建议您将这种实例限制逻辑分离出来,也许放到一个工厂类中。这样做的好处是不会从构造函数中抛出异常。

【讨论】:

    【解决方案3】:

    我会这样做:

    public class Parent  {
    
        public Parent() {
            if (count.incrementAndGet() >= LIMIT) { //count is an AtomicInt/Long
                throw new InstantiationException("Too many instances");
            }
    
        protected Parent(boolean placeholder) { //protected means only subclasses can call it
            //do nothing with the placeholder, but it differentiates the two constructors
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-08
      相关资源
      最近更新 更多