单利模式
程序员文章站
2022-07-04 08:44:30
...
饿汉式
//创建对象
private static Model model = new Model();
//私有构造
private Model(){
}
//获取单列对象
public static Model getInstance(){
return model;
}
懒汉式,也是常用的形式
双重检查[推荐用]
public class Singleton {
private static volatile Singleton singleton = null;
private Singleton() {}
public static Singleton getInstance() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}