突然想到了我第一次面试单例都不太会写,索性这次写一部分
1
package singlePattern;/** * 饿汉式 */public class Singleton1 { private static Singleton1 instance = new Singleton1(); private Singleton1() { } public static Singleton1 getInstance() { return instance; } public static void main(String[] args) { Singleton1 instance = Singleton1.getInstance(); }}复制代码
2
package singlePattern;/** * 饿汉式 */public class Singleton2 { private static Singleton2 instance = null; static { instance = new Singleton2(); } private Singleton2() { } public static Singleton2 getInstance() { return instance; }}复制代码
3
package singlePattern;/** * 懒汉式,但是这种线程不安全,不存在可用性 */public class Singleton3 { public static Singleton3 instance = null; private Singleton3() {} public static Singleton3 getInstance() { if (instance == null) { instance = new Singleton3(); } return instance; }}复制代码
4
package singlePattern;/** * 懒汉式,线程相对安全,效率低,每次getInstance都需要持锁 */public class Singleton4 { private static Singleton4 instance = null; private Singleton4() {} public static synchronized Singleton4 getInstance() { if (instance == null) { instance = new Singleton4(); } return instance; }}复制代码
5
package singlePattern;/** * 懒汉式,但是线程不安全 */public class Singleton5 { private static Singleton5 instance = null; private Singleton5() {} private static Singleton5 getInstance() { if (instance == null) { synchronized (Singleton5.class) { instance = new Singleton5(); } } return instance; }}复制代码
6
package singlePattern;/** * 懒汉式,双重校验锁 */public class Singleton6 { private static Singleton6 instance = null; private Singleton6(){} public static Singleton6 getInstance() { if (instance == null) { synchronized (Singleton6.class) { if (instance == null) { instance = new Singleton6(); } } } return instance; }}复制代码
7
package singlePattern;/** * 内部类,通过静态类初始化时进行instance的创建,类似饿汉式,但是在初始化时别的线程 * 无法干扰,而且也可以在形式上有懒加载的感觉 */public class Singleton7 { private Singleton7(){} private static class SingletonHolder { private static Singleton7 instance = new Singleton7(); } public static Singleton7 getInstance() { return SingletonHolder.instance; }}复制代码
8
package singlePattern;/** * 枚举 */public enum Singleton8 { instance; private Singleton8(){} public void method(){}}复制代码
现在都很推荐用枚举,建议多了解,明天写个相关的博客