单例模式

单例模式的写法

//饿汉(线程不安全,不正确)
class Singleton1 {
    private static Singleton1 instance = new Singleton1();
    private Singleton1(){
    }
    public static Singleton1 getInstance(){         
        return instance;
    }
}
//饱汉(线程安全但是高并发性能不高)
class Singleton2 {
    private static Singleton2 instance;
    private Singleton2(){
        
    }
    public static synchronized Singleton2 getSingleton2(){
        if(instance == null){
            instance = new Singleton2();
        }
        return instance;
    }
}
//线程安全,性能又高,写法常见
class Singleton3{
    private static Singleton3 instance;
    private static byte[] lock = new byte[0];
    private Singleton3(){
        
    }
    public static Singleton3 getInstance() {
        if(instance == null){
            synchronized (lock) {
                if(instance == null){
                    instance = new Singleton3();
                }
            }
        }
        return instance;
    }
}
//线程安全,性能又高的另一种,也很常见
class Singleton4 {
    private static Singleton4 instance;
    private static ReentrantLock lock = new ReentrantLock();
    private Singleton4 () {
        
    }
    public static Singleton4 getInstance() {
        if(instance == null){
            lock.lock();
            if(instance == null){
                instance == new Singleton4();
            }
            lock.unlock();
        }
        return instance;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 单例模式(SingletonPattern)一般被认为是最简单、最易理解的设计模式,也因为它的简洁易懂,是项目中最...
    成热了阅读 4,293评论 4 34
  • 1.单例模式概述 (1)引言 单例模式是应用最广的模式之一,也是23种设计模式中最基本的一个。本文旨在总结通过Ja...
    曹丰斌阅读 3,005评论 6 47
  • 前言 本文主要参考 那些年,我们一起写过的“单例模式”。 何为单例模式? 顾名思义,单例模式就是保证一个类仅有一个...
    tandeneck阅读 2,538评论 1 8
  • 概念 确保某一个类只有一个实例,而且自行实例化,并向整个系统提供一个访问它的全局访问点,这个类称为单例类。 特性 ...
    野狗子嗷嗷嗷阅读 558评论 0 2
  • 我的爱情,经过了恋爱期,过渡期,千锤百炼到今天,他还是那个他,一个外表嚣张,内心柔软的他,他很浪漫,但却不愿用言语...
    未及冬月阅读 276评论 2 0