java设计模式-单例模式

单例模式保证了对象唯一

  1. 饿汉模式,类加载时立即创建对象

    
    private static EagerSingleton INSTANCE = new EagerSingleton();
    
    private EagerSingleton() {
    }
    public static EagerSingleton getInstance() {
      return INSTANCE;
    }
    ```

    </li>
    <li>懒汉模式,在第一次调用时创建对象,存在线程安全问题,可能存在多个对象,解决方法是加锁 ```java
    private static LazySingleton INSTANCE;
    private LazySingleton() {
    }
    /**
    <ul>
    <li>经测试 并发会有问题,大概十个线程会出现三个对象的情况 可以加上synchronized在方法上 1000个线程 167毫秒 耗时
    *使用双重检验 性能会好一点点点</li>
    <li>@return
    */
    public static LazySingleton getInstance() {
    // if (INSTANCE == null) {
    // INSTANCE = new LazySingleton();
    //
    // }
    if (INSTANCE == null) {
    synchronized (LazySingleton.class) {
    if (INSTANCE == null) {
    INSTANCE = new LazySingleton();
    }
    }
    }
    return INSTANCE;
    }
    ```

  2. 静态代码块,等同于饿汉也是类加载时创建
    private static StaticBlockSingleton INSTANCE;
    private StaticBlockSingleton() {
    }
    static {
      INSTANCE = new StaticBlockSingleton();
    }
    public static StaticBlockSingleton getInstance() {
      return INSTANCE;
    }
  3. 内部类,静态内部类方式
    
    private InnerClassSingleton() {
    }
    private static  class Inner{
      private static final InnerClassSingleton INSTANCE = new InnerClassSingleton();
    }
    public static InnerClassSingleton getInstance() {
      return InnerClassSingleton.getInstance();
    }
    ```
  4. 枚举

    public enum EnumSingleton {
    INSTANCE;
    public static void pro() {
      System.out.println("enum instance");
    
    }
    public EnumSingleton getInstance() {
      return INSTANCE;
    }
    }

    2022年9月13日

    @AllArgsConstructor@NoArgsConstructor(access = AccessLevel.NONE)@ToString
    @FieldDefaults(level = AccessLevel.PRIVATE)
    public class InitUser {
     Integer id;
     String ip;
     String code;
    enum InnerEnum {
        INSTANCE;
    
        private InitUser getInstance() {
            return new InitUser(1, "1", "1");
        }
    }
    public static InitUser getInit() {
        return InnerEnum.INSTANCE.getInstance();
    }
    }

202201261653278

Leave a Comment