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

    介绍

    在应用单例模式时,生成单例的类必须保证只有一个实例的存在,很多时候整个系统只需要拥有一个全局对象,才有利于协调系统整体的行为。比如在整个系统的配置文件中,配置数据有一个单例对象进行统一读取和修改,其他对象需要配置数据的时候也统一通过该单例对象来获取配置数据,这样就可以简化复杂环境下的配置管理。--摘自维基百科

    核心

    保证一个类仅有一个实例,并提供一个访问它的全局访问点。

        class Singleton{
            constructor(name) {
                this._name = name;
                this._instance = null;
            }
            getName() {
                console.log(this.name)
            }
            static getInstance() {
                if(!this._instance){
                    this._instance = new Singleton();
                }
                return this._instance;
            }
        }
        let _a = Singleton.getInstance('a');
        let _b = Singleton.getInstance('b');
    

    通过闭包的形式创建单例模式,同时符和惰性单例的特性

        let Singleton = function(name) {
            this._name = name;
        };
    
        Singleton.prototype.getName = function() {
            console.log(this._name)
        };
        Singleton.getInstance = (function(name) {
            let _instance;
            return function(name){
                if (!_instance) {
                    _instance = new Singleton(name);
                }
                return _instance;
            }
        })();
    
        let _a = Singleton.getInstance('a');
        let _b = Singleton.getInstance('b');
        console.log(_a == _b);   //true
    

    引入代理实现单例模式

            class CreateDiv {
                constructor (html){
                    this._html = html;
                    this.init()
                }
                init(){
                    let _div = document.createElement('div');
                    _div.innerHTML  = this._html;
                    document.body.appendChild(_div);
                }
            }
            let _ProxyCreateDiv = (function(){
                let _instance;
                return function(html){
                    !_instance && (_instance = new CreateDiv(html))
                    console.log(_instance)
                }
                return _instance;
            })()
            let _a = new _ProxyCreateDiv('a');
            let _b = new _ProxyCreateDiv('b');
    

    负责管理单例模式的逻辑移到了代理类_ProxyCreateDiv中。这样一来,CreateDiv就变成了一个普通的类,他跟_ProxyCreateDiv组合起来可以达到单例模式的效果

  • 相关阅读:
    其他魔术方法
    类型约束和类的魔术常量
    PHP对象遍历、内置标准类与数据转对象
    类的自动加载与对象的克隆
    PHP重载与接口
    面向对象
    PHP基础
    地下城与勇士的项目整理
    mysql建表
    jQuery
  • 原文地址:https://www.cnblogs.com/mengxiangji/p/10969941.html
Copyright © 2011-2022 走看看