限制类的DIRECT实例数 [英] Limit the number of DIRECT Instances of a class
问题描述
换句话说:一个类如何跟踪它的构造函数是否被实例化它的子类或其实例被直接创建?
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?
[请cosider以下示例代码]:
[Please cosider the following sample code]:
class Parent
{
.............
.........
..............
}
class Child1 extends Parent
{
.............
.........
..............
}
class Child2 extends Parent
{
.............
.........
..............
}
我想限制通过调用创建的
Parent
类的直接实例数new parent(...) / code>和EXCLUDING从计数,父
实例创建由于instatiating任何子类 Child1 $
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
.
推荐答案
你可以做 p>
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?
这篇关于限制类的DIRECT实例数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!