单例模式
单例(Singleton)模式的定义:指一个类只有一个实例,且该类能自行创建这个实例的一种模式。
饿汉式
/**
* 饿汉式
* @author zwzh_zj
*/
public class HungrySingleton {
private static HungrySingleton instance = new HungrySingleton();
private HungrySingleton() {
}
public static HungrySingleton getInstance() {
return instance;
}
}
懒汉式
/***
* 懒汉式
* @author zwzh_zj
*/
public class LazySingleton {
private static volatile LazySingleton lazySingleton = null;
private LazySingleton() {
//private 避免类在外部被实例化?
}
public synchronized LazySingleton getInstance() {
if (lazySingleton == null) {
lazySingleton = new LazySingleton();
}
return lazySingleton;
}
}
参考资料:
1.http://c.biancheng.net/view/1338.html
2.代码地址:https://gitee.com/zhoujie1/design-mode-and-principle.git