读书人

Head First 设计方式学习笔记(五)单

发布时间: 2012-07-19 16:02:19 作者: rapoo

Head First 设计模式学习笔记(五)单例模式

单例模式,都是线程安全的。虽然例1不是绝对安全.

?

例1、

public class Singleton {private static Singleton uniqueInstance; private Singleton() {} public static synchronized Singleton getInstance() {if (uniqueInstance == null) {uniqueInstance = new Singleton();}return uniqueInstance;} }

?

例2、

public class Singleton {private volatile static Singleton uniqueInstance; private Singleton() {} public static Singleton getInstance() {if (uniqueInstance == null) {synchronized (Singleton.class) {if (uniqueInstance == null) {uniqueInstance = new Singleton();}}}return uniqueInstance;}}
?

例3、

?

public class Singleton {private static Singleton uniqueInstance = new Singleton(); private Singleton() {} public static Singleton getInstance() {return uniqueInstance;}}

读书人网 >软件开发

热点推荐