Per-Class 单例,防止额外的实例
Per-Class singleton, prevent additional instances
如何定义三个 类 A、B、C,以便每个都只能实例化一次。换句话说,如果单个 A
已经被实例化,则不能再创建。但是创建一个 B
应该没问题(只要没有先创建其他 B
)。
class A{
}
class B extends A{
}
class C extends B{
}
生产:
A a1 = new A(); //Should work fine
A a2 = new A(); // Should throw an error if one instance is already created
B b1 = new B(); // Should work fine despite A instance is there or not
B b2 = new B(); // Should throw an error
C c1 = new C(); // Should work fine despite B instance is there or not
C c2 = new C(); // Should throw an error
做那样的事情可能不是个好主意,因为仅仅因为已经创建了另一个对象就拒绝构建一个对象是非常"magic-y"的,但这是可能的:
public class A {
private static final Set<Class<?>> INSTANTIATED_CLASSES = new HashSet<Class<?>>();
public A() {
if (!INSTANTIATED_CLASSES.add(this.getClass())) {
throw new IllegalStateException("Oh no! " + this.getClass() + " was already instantiated once!");
}
}
}
这将确保您只能在 A
或其任何子 类.
的实例上精确构造
请注意,像这样的全局状态的一个主要缺点是,如果您不能随意实例化对象,那么测试您的代码将变得非常不同。
如何定义三个 类 A、B、C,以便每个都只能实例化一次。换句话说,如果单个 A
已经被实例化,则不能再创建。但是创建一个 B
应该没问题(只要没有先创建其他 B
)。
class A{
}
class B extends A{
}
class C extends B{
}
生产:
A a1 = new A(); //Should work fine
A a2 = new A(); // Should throw an error if one instance is already created
B b1 = new B(); // Should work fine despite A instance is there or not
B b2 = new B(); // Should throw an error
C c1 = new C(); // Should work fine despite B instance is there or not
C c2 = new C(); // Should throw an error
做那样的事情可能不是个好主意,因为仅仅因为已经创建了另一个对象就拒绝构建一个对象是非常"magic-y"的,但这是可能的:
public class A {
private static final Set<Class<?>> INSTANTIATED_CLASSES = new HashSet<Class<?>>();
public A() {
if (!INSTANTIATED_CLASSES.add(this.getClass())) {
throw new IllegalStateException("Oh no! " + this.getClass() + " was already instantiated once!");
}
}
}
这将确保您只能在 A
或其任何子 类.
请注意,像这样的全局状态的一个主要缺点是,如果您不能随意实例化对象,那么测试您的代码将变得非常不同。