java设计模式之单例模式
2020-07-14 本文已影响0人
淡定得蛋蛋
懒汉模式
public class LazySingle{
//在类加载时不创建实例,因此类加载快,但运行时获取对象慢
//注意,懒汉模式是线程不安全的,需要进行处理
private static LazySingle ins = null;
private LazySingle(){
}
public static LazySingle getInstance(){
if (ins == null){
ins = new LazySingle();
}
return ins;
}
}
懒汉模式处理
public class LazySingle{
private static LazySingle ins = null;
private LazySingle(){
}
//方法加锁
//用synchronized关键词修饰instance方法,同步创建单例对象
public static synchronized LazySingle getInstance(){
if (ins == null){
ins = new LazySingle();
}
return ins;
}
}
饿汉模式
public class EagerSingle{
//在类加载时就完成了初始化,因此类加载较慢,但获取对象快
private static EagerSingle ins = new EagerSingle;
private EagerSingle(){
}
public static EagerSingle getInstance(){
return ins;
}
}