美文网首页
java设计模式之单例模式

java设计模式之单例模式

作者: 淡定得蛋蛋 | 来源:发表于2020-07-14 22:48 被阅读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;
    }
}

相关文章

网友评论

      本文标题:java设计模式之单例模式

      本文链接:https://www.haomeiwen.com/subject/romqhktx.html