原文地址: http://forestqqqq.iteye.com/blog/1896723
一,餓漢式單例
- //餓漢式單例1 ??
- public ? class ?Singleton1?{??
- ???? private ? static ? final ?Singleton1?instance?=? new ?Singleton1();??
- ???? private ?Singleton1(){}??
- ???? public ? static ?Singleton1?getInstance(){??
- ???????? return ?instance;??
- ????}??
- }??
- ??
- //餓漢式單例2 ??
- class ?Singleton{??
- ???? private ? static ? class ?Single{??
- ???????? static ? final ?Singleton?instance?=? new ?Singleton();??
- ????}??
- ???? private ?Singleton(){}??
- ???? public ? static ?Singleton?getInstance(){??
- ???????? return ?Single.instance;??
- ????}??
- }??
?
二,懶漢式單例
- //懶漢式單例 ??
- public ? class ?Singleton2?{??
- ???? private ? static ?Singleton2?instance?=? null ;??
- ???? private ?Singleton2(){}??
- ???? public ? static ? synchronized ?Singleton2?getInstance(){??
- ???????? if (instance?==? null ){??
- ????????????instance?=? new ?Singleton2();??
- ????????}??
- ???????? return ?instance;??
- ????}??
- }??
?
三,DCL雙重鎖檢測式單例
- //DCL雙重鎖檢測式單例 ??
- public ? class ?Singleton3?{??
- ???? private ? volatile ? static ?Singleton3?instance?=? null ;??
- ???? private ?Singleton3(){}??
- ???? public ? static ?Singleton3?getInstance(){??
- ???????? if (instance?==? null ){??
- ???????????? synchronized (Singleton3. class ){??
- ???????????????? if (instance?==? null ){??
- ????????????????????instance?=? new ?Singleton3();??
- ????????????????}??
- ????????????}??
- ????????}??
- ???????? return ?instance;??
- ????}??
- //參考文章:http://www.ibm.com/developerworks/cn/java/j-dcl.html ??
- }??
?
?
四,登記式單例
- import ?java.lang.reflect.Constructor;??
- import ?java.util.HashMap;??
- import ?java.util.Map;??
- ??
- //登記式單例 ??
- public ? class ?Singleton4?{??
- ???? private ?? static ? final ?Map<String,Singleton4>?instances?=??
- ???????????? new ?HashMap<String,Singleton4>();??
- ???? static {??
- ????????Singleton4?instance?=? new ?Singleton4();??
- ????????instances.put(instance.getClass().getName(),?instance);??
- ????}??
- ???? protected ?Singleton4(){}??
- ???? public ? static ? synchronized ?Singleton4?getInstance(String?name){??
- ???????? if (name?==? null ){??
- ????????????name?=?Singleton4. class .getName();??
- ????????}??
- ???????? if (instances.get(name)?==? null ){??
- ???????????? try ?{??
- ????????????????Constructor?con?=?Class.forName(name).getDeclaredConstructor();??
- ????????????????con.setAccessible( true );??
- ????????????????instances.put(name,?(Singleton4)con.newInstance());??
- ????????????}? catch ?(Exception?e)?{??
- ????????????????e.printStackTrace();??
- ????????????}??
- ????????}??
- ???????? return ?instances.get(name);??
- ????}??
- //參考文章:http://www.cnblogs.com/whgw/archive/2011/10/05/2199535.html ??
- }??
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
