java中实现单例的类,如何在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...

}

And here is the concrete implementation:

public class B extends A {

private B() { }

static {

instance = new B();

}

//...implementations of my abstract methods...

}

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;

and this

ClassLoader.getSystemClassLoader().loadClass("B");

A.getInstance() - return null;

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.

I'm using sun-java6-jre on Ubuntu 32bit to run these tests.

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值