在整个系统中,只能存在一个对象实例,也就是说只能new一次
饿汉式:
在系统启动后,就会实例化一个对象(不管用不用得到,我先买了再说)
-
缺点:造成内存浪费(如果从来没有使用过)
-
优点:不会造成线程安全的问题
class EHPatternInstance1{ private final static EHPatternInstance1 INSTANCE = new EHPatternInstance1(); private EHPatternInstance1(){ } public static EHPatternInstance1 getInstance(){ return INSTANCE; } }
懒汉式:
在需要用到的时候才进行实例化(作业等老师快要检查了才做)
-
优点:节省内存,如果永远不会用到,则将不会被创建
-
缺点:需要考虑线程安全问题
class LHPatternThreadUnSafe{ private static LHPatternThreadUnSafe INSTANCE; private LHPatternThreadUnSafe(){ } public static LHPatternThreadUnSafe getInstance(){ if (INSTANCE == null) { INSTANCE = new LHPatternThreadUnSafe(); return INSTANCE; } return INSTANCE; } }
双检锁:
/** * 同步代码块 双重检查 锁住当前类,保证同一时间只有一个实例被创建 */ class LHPatternThreadSafeDoubleCheck{ private static LHPatternThreadSafeDoubleCheck INSTANCE; private LHPatternThreadSafeDoubleCheck(){ } public static LHPatternThreadSafeDoubleCheck getInstance(){ if (INSTANCE == null) { synchronized (LHPatternThreadSafeDoubleCheck.class){ if (INSTANCE == null) { INSTANCE = new LHPatternThreadSafeDoubleCheck(); } } return INSTANCE; } return INSTANCE; } }
标签:return,private,INSTANCE,static,模式,单例,LHPatternThreadSafeDoubleCheck,EHPatternIns From: https://www.cnblogs.com/darkb4dawn/p/18336212