如何在 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.
我在 32 位 Ubuntu 上使用 sun-java6-jre 来运行这些测试.
I'm using sun-java6-jre on Ubuntu 32bit to run these tests.
推荐答案
Abstract 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屋!