设计模式之单例模式

单例模式 确保一个类仅有一个实例,并提供一个访问它的全局访问点

class Window{
    constructor(name){
        this.name=name;
    }
    static getInstance(){   //static 为类上色方法,不能通过实例来访问
        if(!this.instance){
            this.instance = new Window();
        }
        return this.instance;
    }
}

let s1 = Window.getInstance();
let s2 = Window.getInstance();
console.log(s1);
console.log(s2);
console.log(s1===s2);
复制代码

透明单例 本例违反了单一职责原则

let Window = (function (){
    let window;
    let Window = function (name){
        if(window){
            return window;
        }else{
            this.name = name;
            return (window=this)
        }
    }
    return Window;
})();

let w1 = new Window().this;
let w2 = new Window().this;
复制代码

把类的实例创建和单例逻辑分开

function Window (name){
    this.name = name;
}

function Dialog(title, content){
    this.title=title;
    this.content = content;
}

Window.prototype.getName=()=>{
    console.log(this.name);
}

let CreactSingle = function (Counstructor){
    let instance;
    return function (){
        if (!instance) {
            instance = new Counstructor(...arguments);
        }
        return instance;
    }
}

let createWindow = CreactSingle(Window);
let w1 = new createWindow('w1')
let w2 = new createWindow('w2')
console.log(w1===w2);
复制代码

复杂层次对象的可读性要求 实例 jquery

let $={};

$.define = function(namespace, fn){
    let namespaces = namespace.split('.');
    let fnName = namespaces.pop();
    let current =$;
    for (let i = 0; i < namespaces.length;i++){
        let namespace = namespaces[i];
        if (!current[namespace]){
            current[namespace]={};
        }
        current = current[namespace];
    }
    current[fnName]=fn;
}
$.define('dom.addClass', function(){
    console.log('dom.addClass')
})
$.define('dom.attr', function () {
    console.log('dom.attr')
})

$.dom.addClass()
$.dom.attr()
复制代码

实例 模态框

class Login{
    constructor(){
        this.element = document.createElement('div');
        document.body.appendChild(this.element);
    }
    static getInstance(){
        if (!this.instance){
            this.instance = new Login();
        }
        return this.instance;
    }
}
复制代码

实例 redux 只有一个state

function createStore(){
    let state;
    let listeners =[];
    function subscribe(listener){
        listeners.push(listener);
    }
    function getState(){
        return state;
    }
    function dispatch(){
        state = reducer(state, action)
    }
    return {
        subscribe,
        getState,
        dispatch
    }
}

let reducer = function(){

}

let store = createStore(reducer);
复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值