單例模式又可分爲惡漢式和懶漢式:
惡漢式實現方法:
package com.dx.demo;
/**
* 單例模式-惡漢模式
* @author xiangzi
*
*/
public class SingleDemo1 {
private static SingleDemo1 single = new SingleDemo1();
//構造方法私有化
private SingleDemo1(){}
//獲取單例對象
public static SingleDemo1 getInstance(){
return single;
}
//其他方法
public void otherMetod(){
System.out.println("other methods ........");
}
}
package com.dx.demo;
/**
* 測試
* @author xiangzi
*
*/
public class MainTest {
public static void main(String[] args) {
SingleDemo1 single1 = SingleDemo1.getInstance();
SingleDemo1 single2 = SingleDemo1.getInstance();
System.out.println(single1 == single2);
System.out.println("==============================");
single1.otherMetod();
}
}
測試結果:
true
==============================
other methods ........
懶漢式實現:
package com.dx.demo;
/**
* 單例模式-懶漢模式
*
* @author xiangzi
*
*/
public class SingleDemo2 {
private static SingleDemo2 single = null;
//構造方法私有化
private SingleDemo2(){}
//獲取單例對象
public static SingleDemo2 getInstance(){
//多線程下,利用synchronized解決同步問題
synchronized (SingleDemo2.class) {
if(single == null){
single = new SingleDemo2();
}
}
return single;
}
//其他方法
public void otherMetod(){
System.out.println("other methods ........");
}
}
package com.dx.demo;
/**
* 測試
* @author xiangzi
*
*/
public class MainTest {
public static void main(String[] args) {
SingleDemo2 single1 = SingleDemo2.getInstance();
SingleDemo2 single2 = SingleDemo2.getInstance();
System.out.println(single1 == single2);
System.out.println("==============================");
single1.otherMetod();
}
}
測試結果:
true
==============================
other methods ........
總結:惡漢模式下,由於當前對象一旦被jvm加載,就會產生該類的實例(不管有用沒用,先生成實例,所以是惡漢式),以後獲取的都是統一對象,不會產生多線程下產生多個實例。而懶漢式由於只有該類被引用式,纔會創建實例,所以需要解決多線程情況下的資源同步問題。