diff --git a/README.md b/README.md index 78c998a..abcf82b 100644 --- a/README.md +++ b/README.md @@ -41,5 +41,3 @@ if (1 ^ n == n + 1) { ``` --- -版权声明:本文为CSDN博主「wenyixicodedog」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 -原文链接:https://blog.csdn.net/wenyiCodeDog/article/details/105525681 diff --git a/src/main/java/org/example/SingletonClass.java b/src/main/java/org/example/SingletonClass.java new file mode 100644 index 0000000..5632df9 --- /dev/null +++ b/src/main/java/org/example/SingletonClass.java @@ -0,0 +1,114 @@ +package org.example; + +/** + * 7种单例设计模式 + * 1.饿汉式 + * 2.懒汉式 + * 3.懒汉式+同步方法 + * 4.Double check + * 5.Holder 方式 + * 6.Enum 方式 + * 7.Enum Holder + */ +public class SingletonClass { + //懒汉式单例 + public static class StarvingSingleton { + private static final StarvingSingleton INSTANCE = new StarvingSingleton(); + + private StarvingSingleton(){} + + public static StarvingSingleton getInstance(){ + return INSTANCE; + } + } + + //懒汉式单例 + public static class LazyBoneSingleton{ + private static LazyBoneSingleton INSTANCE; + + private LazyBoneSingleton(){} + + public static LazyBoneSingleton getInstance(){ + if (INSTANCE == null){ + INSTANCE = new LazyBoneSingleton(); + } + return INSTANCE; + } + } + + //懒汉式单例+同步方法 + public static class LazyBoneSynchronizedSingleton{ + private static LazyBoneSynchronizedSingleton INSTANCE; + + private LazyBoneSynchronizedSingleton(){} + + public static synchronized LazyBoneSynchronizedSingleton getInstance(){ + if (null == INSTANCE){ + INSTANCE = new LazyBoneSynchronizedSingleton(); + } + return INSTANCE; + } + } + + //Double-check + public static class DoubleCheckSingleton{ + private volatile static DoubleCheckSingleton INSTANCE ; + + private DoubleCheckSingleton(){} + + public static DoubleCheckSingleton getInstance(){ + if (null == INSTANCE){ + synchronized (DoubleCheckSingleton.class){ + if (null == INSTANCE ){ + INSTANCE = new DoubleCheckSingleton(); + } + } + } + return INSTANCE; + } + } + + //Holder + public static class HolderSingleton{ + private HolderSingleton(){} + + private static class Holder{ + private static HolderSingleton instance = new HolderSingleton(); + + public static HolderSingleton getInstance(){ + return Holder.instance; + } + } + } + + //Enum + public enum EnumSingleton{ + INSTANCE; + + public static EnumSingleton getInstance(){ + return INSTANCE; + } + } + + //Enum Holder + public static class EnumHolderSingleton{ + private EnumHolderSingleton(){} + + private enum EnumHolder{ + INSTANCE; + private EnumHolderSingleton instance; + + EnumHolder(){ + this.instance = new EnumHolderSingleton(); + } + + private EnumHolderSingleton getInstance(){ + return instance; + } + } + + public static EnumHolderSingleton getInstance(){ + return EnumHolder.INSTANCE.getInstance(); + } + } +}