如何在Java中实现抽象的单例类? [英] How can I implement an abstract singleton class in Java?
问题描述
以下是我的示例抽象单例类:
Here is my sample abstract singleton class:
public abstract class A {
protected static A instance;
public static A getInstance() {
return instance;
}
//...rest of my abstract methods...
}
以下是具体实现:
public class B extends A {
private B() { }
static {
instance = new B();
}
//...implementations of my abstract methods...
}
不幸的是我无法在B类中获取静态代码来执行,因此实例变量永远不会被设置。我试过这个:
Unfortunately I can't get the static code in class B to execute, so the instance variable never gets set. I have tried this:
Class c = B.class;
A.getInstance() - returns null;
此
ClassLoader.getSystemClassLoader().loadClass("B");
A.getInstance() - return null;
在eclipse调试器中运行这两个,静态代码永远不会被执行。我可以找到执行静态代码的唯一方法是将B的构造函数的可访问性更改为public,并调用它。
Running both these in the eclipse debugger the static code never gets executed. The only way I could find to get the static code executed is to change the accessibility on B's constructor to public, and to call it.
我正在使用sun-java6 -jre在Ubuntu 32bit上运行这些测试。
I'm using sun-java6-jre on Ubuntu 32bit to run these tests.
推荐答案
抽象Singleton?对我来说听起来不太可行。 Singleton模式需要一个 private
构造函数,这已经使得子类化成为不可能。你需要重新考虑你的设计。 抽象工厂模式可能更适合特定用途。
Abstract Singleton? Doesn't sound viable to me. The Singleton pattern requires a private
constructor and this already makes subclassing impossible. You'll need to rethink your design. The Abstract Factory pattern may be more suitable for the particular purpose.
这篇关于如何在Java中实现抽象的单例类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!