问题
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