zoukankan      html  css  js  c++  java
  • 【设计模式系列-创造型模式篇】-单例设计模式

    单例模式定义

    单例模式是一个比较简单的模式,其定义如下:Ensure a class has only one instance,and provide a global point of access to it.确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。

    单例模式应用场景

    1、资源共享的情况下,避免由于资源操作时导致的性能或损耗等。如日志文件,应用配置等。

    2、控制资源的情况下,方便资源之间的互相通信。如线程池等。

    单例模式应用详解

    单例模式主要有两种形式:饿汉式和懒汉式(饱汉式)。

    -饿汉式

    /**
     * 饿汉式
     */
    public class HungrySingleton {
    
        // 私有静态实例对象
        private static final HungrySingleton singleton  = new HungrySingleton();
    
        // 私有构造方法
        private HungrySingleton(){};
    
        // 公共静态方法
        public static HungrySingleton getInstance(){
            return singleton;
        }
    
    }

    -懒汉式

    /**
     * 懒汉式
     */
    public class LazySingleton {
        
        private static LazySingleton singleton = null;
        
        private LazySingleton(){};
        
        public static LazySingleton getInstance(){
            if (singleton != null){
                singleton = new LazySingleton();
            }
            return singleton;
        }
    }

    两种方式对比

    饿汉式单例写起来很简单,线程安全。但是当该类被加载的时候,会初始化该实例和静态变量并分配内存空间,一直占用内存。

    饱汉式单例写起来很简单,只有第一次调用的时候才会初始化,节省了内存。但是线程不安全,多个线程调用可能会出现多个实例。

    单例模式设计思想

    1、静态实例变量,带有static关键字的属性在每一个类中都是唯一的。

    2、私有化构造方法,限制客户端随意创造实例,此为保证单例的最重要的一步。

    3、提供一个公共的获取实例的静态方法,注意,是静态的方法,因为这个方法是在我们未获取到实例的时候就要提供给客户端调用的,所以如果是非静态的话,那就变成一个矛盾体了,因为非静态的方法必须要拥有实例才可以调用。

  • 相关阅读:
    Warning: Cannot modify header information
    curl_setopt(): CURLOPT_FOLLOWLOCATION cannot be activated when in safe_mode or an open_basedir is set in
    PHP Warning: strtotime(): It is not safe to rely on the system's timezone settings.
    出现Deprecated: Function ereg_replace() is deprecated in 的原因及解决方法
    APMServ5.2.6 升级PHP版本 到高版本 5.3,5.4
    Apache无法启动解决 the requested operation has failed
    用json获取拉钩网的信息
    json
    如何用组件组装一个简单的机器人
    vue-组件
  • 原文地址:https://www.cnblogs.com/ysdrzp/p/10014799.html
Copyright © 2011-2022 走看看