设计模式

1. 单例模式

每次实例化后的对象都一样new Singleton===new Singleton=>true

ES5

function Singleton(){
    // 判断是否存在实例
    if (typeof Singleton.instance === 'object') {
        return Singleton.instance;
    }
    // 缓存
    Singleton.instance = this;
}

ES6

class Singleton{
    static instance 
    constructor(){
        if(typeof Singleton.instance==='object'){
            return Singleton.instance
        }
        Singleton.instance=this;
    }
}

2. 构造函数模式

构造函数当成普通函数使用来实现 Person(123) instanceof Person=>true,不过方法最好写在原型链上,
当有大批量的实例的话,可以共享资源,就会节约很多内存

ES5

function Person(age){
     if (!(this instanceof Person)) {
        return new Person(age);
    }
    this.age = age;
}

ES6

class Person{
    constructor(){

    }
}

ES6中,会抛出异常Cannot call a class as a function

3. 职责链模式

从第一个对象开始,链中收到请求的对象亲自处理它,然后处理完毕后转发给链中的下一个处理者

class Handle{
    constructor(func,handle){
        this._func=func;
        this._next=handle;
    }
    invoke(){
        (this._func||(()=>{}))()
        if(this._next) this._next.invoke()
    }
}
待续。。。。

参考链接

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容