基本设计模式

  • 单例模式
    ES5
function Duck1(name:string){
    this.name=name
    this.instance=null
}

Duck1.prototype.getName=function(){
    console.log(this.name)
}

Duck1.getInstance=function(name:string){
    if(!this.instance){
        this.instance= new Duck1(name)
    }
}
const a=Duck1.getInstance('a')
const b=Duck1.getInstance('b')

console.log(a===b) // true

ES6

class Duck{
    name="xxx"
    static instance:any=null
    action(){
        console.log('123')
    }
    static getInstance(){
       if(!this.instance){
            this.instance=new Duck()
       } 
       return this.instance
    }
}


const obj1=Duck.getInstance()
const obj2=Duck.getInstance()

console.log(obj1===obj2) // true
  • 工厂模式
class Duck{
    name="xxx"
    constructor(name:string){
        this.name=name
    }   
}

function factory(name:string){
    return new Duck(name)
}

const a=factory('x')
const b=factory('s')

  • 策略模式
    代码里有多个if的情况时,做成策略模式,好处:
    策略模式利用组合,委托等技术和思想,有效的避免很多if条件语句
    策略模式提供了开放-封闭原则,使代码更容易理解和扩展
    策略模式中的代码可以复用
    策略模式优化的例子
    `
  • 代理模式
class Duck{
    
    name="xxx"

    constructor(name:string){
        this.name=name
    }   

    getName(){
        console.log('name: ',this.name)
    }
    setName(newValue:string){
        this.name=newValue
    }
}

const tp=new Duck('a')

const obj = new Proxy(tp,{
    set:function(target,property,value){
        return Reflect.set(target,property,'new:'+value)
    },
    get(target,property){
        if(property==='getName'){
            return function(value:String){
                 Reflect.get(target,property,'new:'+value)
            }
        }
        return Reflect.get(target,property)
    }
})

console.log(obj.name)

obj.setName('jack')

console.log(obj.name)

输出:
请添加图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值