首页 > 代码库 > 单例模式--延时初始化

单例模式--延时初始化

基本单例模式:

final class Singleton{
private static Singleton s=new Singleton(47);
private int i;
private Singleton(int x){i=x;}

public static Singleton getReference(){
return s;
}
public int getValue(){return i;}
public void setValue(int x){i=x;}
}

静态延时初始化:
final class StaticSingleton{
private static StaticSingleton s;
private int i;
private StaticSingleton(int x){i=x;}

public static StaticSingleton getReference(){
if(s == null){
s=new StaticSingleton(47);
}
return s;
}

public int getValue(){return i;}
public void setValue(int x){i=x;}
}
类加载延时初始化:
final class InnerSingleton{
private static InnerSingleton s;
private int i;
private InnerSingleton(int x){i=x;}

private static class SingletonHolder{
static InnerSingleton instance =new InnerSingleton(47);
}
public static InnerSingleton getReference(){
return SingletonHolder.instance;
}

public int getValue(){return i;}
public void setValue(int x){i=x;}
}

单例模式--延时初始化