java设计模式之单例模式

懒汉模式
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;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。