1、餓漢式
1)簡單的餓漢式:
Public class ehanshiSingleton{
? ? ?Private ehanshiSingleton(){
}
? ? ?Private final static ehanshiSingleton? h = new ehanshiSingleton();
? ? ?Public static ehanshiSingleton getSingleton(){
? ? ? ? ?Return lhanshiSingleton.h;
}
}

2)靜態(tài)代碼寫法:
Public class ehanshiSingleton{
? ? ?Private ehanshiSingleton(){
}
? ? ?Private final static ehanshiSingleton? h;
? ? ?Static{
? ? ?h=ehanshiSingleton();
}
? ? ?Public static ehanshiSingleton getSingleton(){
? ? ? ? ?Return lhanshiSingleton.h;
}
}
以上兩種寫法執(zhí)行是一樣的,在類初始化是建立一個(gè)對(duì)象,當(dāng)調(diào)用靜態(tài)方法時(shí)返回同一個(gè)對(duì)象的實(shí)例,符合單例設(shè)計(jì)的設(shè)計(jì)思想,如使用較多的情況下會(huì)消耗很多資源;有些單例類使用較少,造成資源浪費(fèi);
2、懶漢式
1)簡單的懶漢式:
Public class lhanshiSingleton{
? ? ?Private lhanshiSingleton(){
}
? ? ?Private static lhanshiSingleton? lanhanshiSingleton;
? ? ?Public static lhanshiSingleton getSingleton(){
? ? ? ? If(lanhanshiSingleton==null){
? ? ? ? ? ? ?Return new lhanshiSingleton();
}
? ? ? ? Return lanhanshiSingleton;
}
}
2)加鎖后的懶漢式:
Public class lhanshiSingleton{
? ? ?Private lhanshiSingleton(){
}
? ? ?Private static lhanshiSingleton? lanhanshiSingleton;
? ? ?Public static synchronized lhanshiSingleton getSingleton(){
? ? ? ? If(lanhanshiSingleton==null){
? ? ? ? ? ? ?Return new lhanshiSingleton();
}
? ? ? ? Return lanhanshiSingleton;
}
}
3)雙重檢查鎖懶漢式:
Public class lhanshiSingleton{
? ? ?Private lhanshiSingleton(){
}
? ? ?Private static lhanshiSingleton? lanhanshiSingleton;
? ? ?Public static lhanshiSingleton getSingleton(){
? ? ? ?Synchronized(lhanshiSingleton.class){
? ? ? ? ?If(lanhanshiSingleton==null){
? ? ? ? ? ?Return new lhanshiSingleton();
}
? ? ? ? ? ??
}
? ? ? ? Return lanhanshiSingleton;
}
}
以上便是單例模式的基本寫法;