JavaScript 装饰器模式

216 阅读1分钟

装饰器模式,就是锦上添花233
大概意思就是,你配置了一个主机,在机箱上配置了很多都灯带,甚至是手办。
灯带和手办并不影响主机的运行,这就是装饰器模式 es7 已经有了装饰器

function leds(target) {

    // 事例方法
    target.prototype.leds = () => {
        console.log(`光污染`)
    }
    
    // 静态方法
    target.garageKit = () => {
        console.log(`手办`)
    }
}

function paint(target, name, descriptor) {
    descriptor.value = () => {
        console.log(`贴上了痛贴`)
    }
}


@leds // 类装饰器
class ComputerHost {
    
    
    @paint // 方法装饰器
    box(){
        console.log(`黑色`)
    }
    
    cpu(){}
    
    powerSupply(){}
    
    ...
}

const myHost = new ComputerHost()
myHost.leds() // 光污染
myHost.box() // 贴上了痛贴