剑指offer ---实现Singleton模式

实现单例

  1. 懒汉模式 当要第一次调用才实例化 避免内存浪费 需要加锁synchronized 才能线程安全
    //双重检查加锁
    public Singleton getInstance() {
        //先检查实例是否为空 不为空进入代码块
        if (instance == null) {
             //同步块 线程安全地创建实例
            synchronized (Singleton.class) {
                 //再次检查实例是否为空 为空才真正的创建实例
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
    //给方法加上同步
    public synchronized Singleton getInstance1() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
  1. 饿汉模式 类加载时候就实例化了 浪费内存
public Singleton2 getInstance(){
        return instance;
    }

猜你喜欢

转载自blog.csdn.net/hxz6688/article/details/53192616