zoukankan      html  css  js  c++  java
  • 单例模式 (学习笔记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中,相当于生成了一个对象池,从池中取用。

  • 相关阅读:
    断棍构造过程-波利亚翁方案-中餐馆过程
    狄利克雷过程
    狄利克雷分布
    共轭先验(conjugate prior)
    镜像与文件系统
    Oracle-04
    Oracle-02
    Oracle-01
    认识数据库
    c:forEach的作用
  • 原文地址:https://www.cnblogs.com/huiy/p/15554678.html
Copyright © 2011-2022 走看看