目录
单例模式是指在内存中会创建且仅创建一次对象的设计模式。
- public class SingletonEH{
-
- private static SingletonEH instance = new SingletonEH();
- private SingletonEH(){}
- public static SingletonEH getInstance() {
- System.out.println("instance:"+instance);
- System.out.println("加载饿汉式....");
- return instance;
- }
- /**
- *是否 Lazy 初始化:否
- *是否多线程安全:是
- *实现难度:易
- *描述:这种方式比较常用,但容易产生垃圾对象。
- *优点:没有加锁,执行效率会提高。
- *缺点:类加载时就初始化,浪费内存。
- *它基于 classloder 机制避免了多线程的同步问题,
- * 不过,instance 在类装载时就实例化,虽然导致类装载的原因有很多种,
- * 在单例模式中大多数都是调用 getInstance 方法,
- * 但是也不能确定有其他的方式(或者其他的静态方法)导致类装载,
- * 这时候初始化 instance 显然没有达到 lazy loading 的效果。
- */
- }
- public class SingletonLH{
-
- private static SingletonLH instance;
- private SingletonLH(){}
-
- public static SingletonLH getInstance(){
- if(instance == null)
- {
- instance = new SingletonLH();
- }
- return instance;
- }
- /**
- *是否 Lazy 初始化:是
- *是否多线程安全:否
- *实现难度:易
- *描述:这种方式是最基本的实现方式,这种实现最大的问题就是不支持多线程。因为没有加锁
- synchronized,所以严格意义上它并不算单例模式。
- *这种方式 lazy loading 很明显,不要求线程安全,在多线程不能正常工作。
- */
- }
- public class SingletonLH{
- //使用volatile关键字可以防止指令重排序,且线程每次操作该变量时都需要先获取它
- private static volatile SingletonLH instance;
- private SingletonLH(){}
-
- public static SingletonLH getInstance(){
- if(instance == null)
- {
- synchronized(SingletonLH.class){
- if(instance == null) //防止前一个线程已经初始化了
- instance = new SingletonLH();
- }
- }
- return instance;
- }
-
- }