设计模式之单例模式

单例模式(Singleton)的目的是为了保证在一个进程中,某个类有且仅有一个实例。

第 1 种:懒汉式单例

public class LazySingleton {

    // 将自身实例化对象设置为一个属性,并用static修饰
    private static LazySingleton instance;
    
    // 构造方法私有化
    private LazySingleton() {}
    
    // 静态方法返回该实例
    public static LazySingleton getInstance() {
        if(instance == null) {
            instance = new LazySingleton();
        }
        return instance;
    }
}

第 2种:饿汉式单例

public class HungrySingleton {

    // 将自身实例化对象设置为一个属性,并用static、final修饰
    private static final HungrySingleton INSTANCE = new HungrySingleton();
    
    // 构造方法私有化
    private HungrySingleton() {}
    
    // 静态方法返回该实例
    public static HungrySingleton getInstance() {
        return INSTANCE;
    }
}

第 3种:线程安全的“懒汉模式”

public class Singleton {

    // 将自身实例化对象设置为一个属性,并用static修饰
    private static Singleton instance;
    
    // 构造方法私有化
    private Singleton() {}
    
    // 静态方法返回该实例,加synchronized关键字实现同步
    public static synchronized Singleton getInstance() {
        if(instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

第4种:单锁以及双重锁

public class LazySingleton {
    private static volatile LazySingleton instance = null;    //保证 instance 在所有线程中同步
    private LazySingleton() {
    }    //private 避免类在外部被实例化
    public static synchronized LazySingleton getInstance() {
        //getInstance 方法前加同步
        if (instance == null) {
            instance = new LazySingleton();
        }
        return instance;
    }
}
public class Singleton {

    // 将自身实例化对象设置为一个属性,并用static修饰
    private static Singleton instance;
    
    // 构造方法私有化
    private Singleton() {}
    
    // 静态方法返回该实例
    public static Singleton getInstance() {
        // 第一次检查instance是否被实例化出来,如果没有进入if块
        if(instance == null) {
            synchronized (Singleton.class) {
                // 某个线程取得了类锁,实例化对象前第二次检查instance是否已经被实例化出来,如果没有,才最终实例出对象
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

第5种:静态内部类

public sealed class Singleton
    {
        public static class SingletonHolder{
       		 private static final Singleton INSTANCE=new Singleton();
        }
        
        private Singleton() { }
        public static final Singleton GetInstance()
        {
            return SingletonHolder.INSTANCE;
        }
    }

第6种:枚举

public enum Singleton{
    INSTANCE;
    public void anyMethod(){
        
    }
}

posted on 2021-11-26 17:10  Chase_Hanky  阅读(42)  评论(0)    收藏  举报