关于java:单例模式

74次阅读

共计 1883 个字符,预计需要花费 5 分钟才能阅读完成。

  1. 懒汉模式
/**
 * @Description 懒汉模式 实现了提早加载, 然而效率较低
 * @Author wanghognbo
 * @Date 2021/9/1
 */
public class LazySingleton {

    private static LazySingleton lazySingleton;

    private LazySingleton(){}

    public synchronized static LazySingleton getLazySingleton(){if(lazySingleton == null){lazySingleton = new LazySingleton();
        }
        return lazySingleton;
    }

    public static void main(String[] args) {LazySingleton h1 = LazySingleton.getLazySingleton();
        LazySingleton h2 = LazySingleton.getLazySingleton();
        System.out.println(h1==h2);
    }
}
  1. 饿汉模式
1
/**
 * @Description  饿汉模式
 * 类加载时实现实例化, 防止多线程同步问题
 * 使类加载的状况有多种, 所以可能造成空间节约
 */
public class HungrySingleton {private static HungrySingleton singleton = new HungrySingleton();

    private HungrySingleton(){}

    public static HungrySingleton getSingleton(){return singleton;}

    public static void main(String[] args) {HungrySingleton h1 = HungrySingleton.getSingleton();
        HungrySingleton h2 = HungrySingleton.getSingleton();
        System.out.println(h1==h2);
    }
}
  1. 双重校验锁模式
/***
* @description: 1. 懒加载, 2 volatile 保障了指令不会重排
*/
public class DoubleCheckSingleton {

    private volatile static DoubleCheckSingleton singleton;

    private DoubleCheckSingleton() {}

    public static DoubleCheckSingleton getInstance(){if(singleton == null){synchronized (DoubleCheckSingleton.class){if(singleton == null){singleton = new DoubleCheckSingleton();
                }
            }
        }
        return singleton;
    }

    public static void main(String[] args) {DoubleCheckSingleton d1 = DoubleCheckSingleton.getInstance();
       DoubleCheckSingleton d2 = DoubleCheckSingleton.getInstance();
        System.out.println(d1==d2);
    }

}
  1. 外部类模式
/***
* @description: 外部类加载时不会加载外部类, 应用外部类时才会加载, 保障了懒加载
 * 类加载时实例化对象, 不会造成线程平安问题
*/
public class InnerClassSingleton {private InnerClassSingleton(){ }

    private static class innerInstance {private static final InnerClassSingleton singleton = new InnerClassSingleton();
    }

    public static InnerClassSingleton getInstance(){return innerInstance.singleton;}

    public static void main(String[] args) {InnerClassSingleton i1 = InnerClassSingleton.getInstance();
        InnerClassSingleton i2 = InnerClassSingleton.getInstance();
        System.out.println(i1==i2);
    }

}

正文完
 0