面试题复习-常用设计模式-单例模式
饿汉式:
package com.ajax.pattern.singleton; import lombok.AccessLevel; import lombok.AllArgsConstructor; @AllArgsConstructor(access = AccessLevel.PRIVATE) public class Singleton { private static Singleton singleton = new Singleton(); public static Singleton getInstance() { return singleton; } }
懒汉式:
package com.ajax.pattern.singleton; import lombok.AccessLevel; import lombok.AllArgsConstructor; @AllArgsConstructor(access = AccessLevel.PRIVATE) public class SingletonEx { private static volatile SingletonEx instance = null; public static SingletonEx getInstance() { if (instance == null) { synchronized (SingletonEx.class) { if (instance == null) { instance = new SingletonEx(); } } } return instance; } }
枚举:——