1. 程式人生 > >java單列模式

java單列模式

1 懶漢式

public class SingletonTest1 {

private static SingletonTest1 single = null;

//懶漢式
public static SingletonTest1 getInstane(){
	if(null == single){
		synchronized (SingletonTest1.class) {
			if(null == single){
				single = new SingletonTest1();
			}
		}
	}
	return single;
}

private  SingletonTest1() {
	super();
}

public static void main(String[] args) {
	SingletonTest1 s1 = SingletonTest1.getInstane();
	SingletonTest1 s2 = SingletonTest1.getInstane();
	if(s1 == s2){
		System.out.println("true");
	}
}


}

2 餓漢式

public class SingletonTest2 {

private static SingletonTest2 single = new SingletonTest2();


public static SingletonTest2 getInstane(){
	return single;
}

private  SingletonTest2() {
	super();
}

public static void main(String[] args) {
	SingletonTest2 s1 = SingletonTest2.getInstane();
	SingletonTest2 s2 = SingletonTest2.getInstane();
	if(s1 == s2){
		System.out.println("true");
	}
}

}