设计模式之-单列模式

2021-05-31  本文已影响0人  姝然

设计模式-单列模式8种方式

1.饿汉式(静态常量)

class Singleton {
  private Singleton() {}

  private final static Singleton instance = new Singleton();
  
  public static Singleton getInstance() {
    return instance;
  }
  
}

2.饿汉式(静态代码块)

class Singleton {
    
    private Singleton() {
        
    }
    
    private  static Singleton instance;
    
    static { 
        instance = new Singleton();
    }
    
    public static Singleton getInstance() {
        return instance;
    }
    
}

3.懒汉式(线程不安全)

class Singleton {
    private static Singleton instance;
    
    private Singleton() {}
    
    //提供一个静态的公有方法,当使用到该方法时,才去创建 instance
    //即懒汉式
    public static Singleton getInstance() {
        if(instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

4.懒汉式(线程安全,同步方法)

class Singleton {
    private static Singleton instance;
    
    private Singleton() {}
    
    //提供一个静态的公有方法,加入同步处理的代码,解决线程安全问题
    //即懒汉式
    public static synchronized Singleton getInstance() {
        if(instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

5.懒汉式(线程不安全,同步代码块)

class Singleton {
    private static Singleton instance;
    
    private Singleton() {}
    
    //提供一个静态的公有方法,加入双重检查代码,解决线程安全问题, 同时解决懒加载问题
    //同时保证了效率, 推荐使用
    
    public static Singleton getInstance() {
        if(instance == null) {
            synchronized (Singleton.class) {
                instance = new Singleton();
            }
        }
        return instance;
    }
}

6.懒汉式(双重检查,线程安全)

class Singleton {
    private static volatile Singleton instance;
    
    private Singleton() {}
    
    //提供一个静态的公有方法,加入双重检查代码,解决线程安全问题, 同时解决懒加载问题
    //同时保证了效率, 推荐使用
    
    public static synchronized Singleton getInstance() {
        if(instance == null) {
            synchronized (Singleton.class) {
                if(instance == null) {
                    instance = new Singleton();
                }
            }
            
        }
        return instance;
    }
}

7.静态内部类

class Singleton {
    private static volatile Singleton instance;
    
    //构造器私有化
    private Singleton() {}
    
    //写一个静态内部类,该类中有一个静态属性 Singleton
    private static class SingletonInstance {
        private static final Singleton INSTANCE = new Singleton(); 
    }
    
    //提供一个静态的公有方法,直接返回SingletonInstance.INSTANCE
    
    public static synchronized Singleton getInstance() {
        
        return SingletonInstance.INSTANCE;
    }
}

8.枚举单列

enum Singleton {
    INSTANCE; //属性
    public void hello() {
        System.out.println("hello~");
    }
}
上一篇 下一篇

猜你喜欢

热点阅读