单例模式:
- 单例类只能有一个实例。
- 单例类必须自己创建自己的唯一实例。
- 单例类必须给所有其他对象提供这一实例。
//懒汉 class Singleton1{ private static Singleton1 instance = null; private Singleton1(){} public static Singleton1 getInstance(){ if (instance != null){ instance = new Singleton1(); } return instance; } } //饿汉 class Singleton2{ private static final Singleton2 instance = new Singleton2(); private Singleton2(){} public static Singleton2 getInstance(){ return instance; } } //枚举 class Singleton3{ private Singleton3(){} private enum Singleton{ INSTANCE; private final Singleton3 instance; private Singleton(){ instance = new Singleton3(); } private Singleton3 getInstance(){ return instance; } } public Singleton3 getInstance(){ return Singleton.INSTANCE.getInstance(); } } //双重校验锁 class Singleton4{ private static volatile Singleton4 instance; private Singleton4(){} public static Singleton4 getInstance(){ if(instance == null){ synchronized (instance){ if (instance == null){ instance = new Singleton4(); } } } return instance; } }
标签:getInstance,private,instance,static,模式,单例,Singleton3 From: https://www.cnblogs.com/thh19201420/p/16776045.html