单例模式 (学习笔记3)

原文地址:http://c.biancheng.net/view/1338.html

使用场景:

  1. 只需要一份对象实例的时候,例如:缓存池,实时信息等。

好处:

  1. 不需要频繁创建和释放对象,保证效率。
  2. 只占用一份内存,使用最少的资源。

示例代码:

  1. 懒汉模式
  2. public class LazySingleton {
        private static volatile LazySingleton instance = null;    //保证 instance 在所有线程中同步
    
        private LazySingleton() {
        }    //private 避免类在外部被实例化
    
        public static synchronized LazySingleton getInstance() {
            //getInstance 方法前加同步
            if (instance == null) {
                instance = new LazySingleton();
            }
            return instance;
        }
    }
  3. 饿汉模式
public class HungrySingleton {
    private static final HungrySingleton instance = new HungrySingleton();

    private HungrySingleton() {
    }

    public static HungrySingleton getInstance() {
        return instance;
    }
}

单例模式也可以加以扩展成有限多例模式,存放在list中,相当于生成了一个对象池,从池中取用。

posted @ 2021-11-15 09:56  huiy_小溪  阅读(23)  评论(0编辑  收藏  举报