zoukankan      html  css  js  c++  java
  • 设计模式之单例模式

    作为对象的创建模式,单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。这个类称为单例类。

    单例模式的特点:

    • 单例类只能有一个实例。
    • 单例类必须自己创建自己的唯一实例。
    • 单例类必须给所有其他对象提供这一实例。 

     饿汉式单例类

     1 public class EagerSingleton {
     2     private static EagerSingleton instance = new EagerSingleton();
     3     /**
     4      * 私有默认构造子
     5      */
     6     private EagerSingleton(){}
     7     /**
     8      * 静态工厂方法
     9      */
    10     public static EagerSingleton getInstance(){
    11         return instance;
    12     }
    13 }

    在这个类被加载时,静态变量instance会被初始化,此时类的私有构造子会被调用。这时候,单例类的唯一实例就被创建出来了。

    懒汉式单例类

    public class LazySingleton{
        private static LazySingleton instance = null;
        /**
         * 私有默认构造子
         */
        private LazySingleton(){}
        /**
         * 静态工厂方法
         */
        public static synchronized LazySingleton getInstance(){
            if(instance == null){
                instance = new LazySingleton();
            }
            return instance;
        }
    }

    懒汉式单例类实现里对静态工厂方法使用了同步化,以处理多线程环境。

    懒汉式是典型的时间换空间,就是每次获取实例都会进行判断,看是否需要创建实例,浪费判断的时间。当然,如果一直没有人使用的话,那就不会创建实例,则节约内存空间。

  • 相关阅读:
    不可或缺 Windows Native (15)
    不可或缺 Windows Native (14)
    不可或缺 Windows Native (13)
    不可或缺 Windows Native (12)
    不可或缺 Windows Native (11)
    不可或缺 Windows Native (10)
    不可或缺 Windows Native (9)
    不可或缺 Windows Native (8)
    不可或缺 Windows Native (7)
    不可或缺 Windows Native (6)
  • 原文地址:https://www.cnblogs.com/cbxBlog/p/9118676.html
Copyright © 2011-2022 走看看