Java 单例设计模 两种方式

2019-04-14 21:30发布

Java 单例设计模式 两种方式:   package cn.itcast.thread; class HungrySingle { private HungrySingle(){} private static final HungrySingle HUNGRY_SINGLE = new HungrySingle(); public static HungrySingle getInstance() { return HUNGRY_SINGLE; } } class LazySingle { private LazySingle(){} private static LazySingle LAZY_SINGLE = null; public static LazySingle getInstance() { if (LAZY_SINGLE == null) { synchronized (LazySingle.class) { if (LAZY_SINGLE == null) { LAZY_SINGLE = new LazySingle(); } } } return LAZY_SINGLE; } } public class SingleDemo { public static void main(String[] argStrings) { HungrySingle hungrySingle = HungrySingle.getInstance(); System.out.println(hungrySingle.toString()); LazySingle lazySingle = LazySingle.getInstance(); System.out.println(lazySingle.toString()); } }