单例模式
程序员文章站
2022-04-15 16:37:53
...
1、饿汉模式
public class HungrySingleton { private static HungrySingleton hungrySingleton = new HungrySingleton(); private HungrySingleton() { } public static HungrySingleton getInstance() { return hungrySingleton; } }
2、懒汉模式
public class HoonSyncSingleton { private static HoonSyncSingleton hoonSingleton = null; private HoonSyncSingleton() { } public synchronized static HoonSyncSingleton getInstance() { if(hoonSingleton == null) { hoonSingleton = new HoonSyncSingleton(); } return hoonSingleton; } }
3、DCL模式
public class DCL { private static DCL instance = null; private DCL() { } public static DCL getInstance() { if(instance == null) { synchronized (DCL.class) { if(instance == null) { instance = new DCL(); } } } return instance; } }
4、内部类模式:
public class HolderDemo { private HolderDemo() { } private static class Holder { private static HolderDemo instance = new HolderDemo(); } public static HolderDemo getInstance() { return Holder.instance; } }
5、枚举模式:
public class EnumSingletonDemo { private EnumSingletonDemo() { } private enum EnumSingleton { INSTANCE; private EnumSingletonDemo instance; EnumSingleton() { instance = new EnumSingletonDemo(); } public EnumSingletonDemo getInstance() { return instance; } } public EnumSingletonDemo getInstance() { return EnumSingleton.INSTANCE.getInstance(); } }