Limit the number of DIRECT Instances of a class

2019-07-19 18:12发布

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.

3条回答
啃猪蹄的小仙女
2楼-- · 2019-07-19 18:57

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?

查看更多
Rolldiameter
3楼-- · 2019-07-19 19:08

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.

查看更多
孤傲高冷的网名
4楼-- · 2019-07-19 19:12

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
    }

}
查看更多
登录 后发表回答