java 中的单态是怎么实现的?

来源:百度知道 编辑:UC知道 时间:2024/07/07 11:12:38
最好举个例子,谢谢!

最简单的实现

public class Singleton {
private static Singleton inst = new Singleton();

private Singleton(){}//构造方法私有,外面就不能new这个对象了
public static Singleton getInstance() {
return inst;//返回的永远是同一个inst
}
}

public class A{
private static instance = null;

private A(){};

public static A getInstance(){
if(instance == null){
synchronized(A.class){
if(instance == null){
instance = new A();
}
}
}
return instance;
}
}

支持一下一楼!呵呵。。可以!
还有一种方式是用同步实现!代码:
public class Singleton {

private static Singleton instance;

private Singleton(){}//必须是私有。

public static Singleton getInstance() {
if instance == null
{
synchronized(Singleton.class)
{
instance = new Singleton() ;