单例模式
简介
确保整个服务一个对象只被初始化一次
懒汉模式:调用方法时候才初始化
public class LazyMode { private LazyMode() { } private static volatile LazyMode hungryMode; public static LazyMode getInstance() { if (hungryMode == null) { synchronized (LazyMode.class) { if (hungryMode == null) { hungryMode = new LazyMode(); } } } return hungryMode; } }
饿汉模式:容器初始化时候就已经初始化
public class HungerMode { private HungerMode() { } private static final HungerMode fullMode = new HungerMode(); public static HungerMode getInstance() { return fullMode; } }
枚举实现单例
public enum EnumMode { SINGLE; private ThreadPoolExecutor threadPoolExecutor; EnumMode() { threadPoolExecutor = new ThreadPoolExecutor(5, 5, 100, TimeUnit.SECONDS, new LinkedBlockingDeque()); } public void startTask(Runnable runnable) { threadPoolExecutor.execute(runnable); } }