您的位置:首页 > 其它

设计模式之单例模式

2016-04-08 02:12 302 查看
/**
* 懒汉式,线程安全单例模式,双重校验锁DCL
*/
public class Lazy {
//禁止new
private Lazy() {
}
//声明静态变量,只执行一次
private volatile static Lazy lazy = null;
//公开方法,返回实例对象
public static Lazy getInstance() {
if (lazy == null) {
synchronized (Lazy.class) {
if (lazy == null)
lazy = new Lazy();
}
}
return lazy;
}
}


/**
* 恶汉式单例模式
*/
public class Singleton {
//禁止new
private Singleton() {
}
//实例化,静态对象,只执行一次
private static Singleton instance = new Singleton();
//公开方法,返回实例对象
public static Singleton getInstance() {
return instance;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: