Limit the number of DIRECT Instances of a class

心不动则不痛 提交于 2019-12-24 04:59:09

问题


To put in other words: How can a class track whether its constructor is called due to instantiating its child class or its instance is directly created?

[Please cosider the following sample code]:

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

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

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

I want to limit number of direct instances of Parent class created by calling new Parent(...), and EXCLUDING from the count, the number of Parent instances created due to instatiating any of the child classes Child1 or Child2.


回答1:


You can do

static final AtomicInteger count = new AtomicInteger();

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

Can you explain why you would want to do this? What do you want to happen when the limit is reached?




回答2:


If you care to follow it, single responsibility principle would suggest you separate out this logic of instance limiting, perhaps into a factory class. This would have the benefit of not throwing exceptions from a constructor.




回答3:


I would do this:

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
    }

}


来源:https://stackoverflow.com/questions/8082860/limit-the-number-of-direct-instances-of-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!