JavaScript设计模式:一、装饰者模式(原型链)

序、设计模式分类
一、装饰者模式(原型链)
二、策略模式
三、代理模式
四、发布订阅模式
五、迭代器模式
六、工厂模式
七、外观模式
八、状态模式
九、单例模式
十、适配器模式

参考:

https://blog.csdn.net/userkang/article/details/104533641

https://www.cnblogs.com/gaosirs/p/10756503.html

装饰器模式(Decorator Pattern)允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装。

枪击大战例子

// 被装饰的玩家
class Player {
    constructor(name) {
        this.name = name
    }

    sayName() {
        console.log(`I am ${this.name}`)
    }

    fire() {
        console.log('I can only punch!')
    }
}

// 装饰器——手枪
class Pistol {
    constructor(player) {
        player.fire = this.fire
    }

    fire() {
        console.log('I shoot with my Pistol!')
    }
}

//装饰器——Kar98狙击步枪
class Kar98 {
    constructor(player) {
        player.fire = this.fire
    }

    fire() {
        console.log('I shoot with my Kar98!')
    }
}

// 新玩家
const player = new Player('zkk')

//打招呼
player.sayName() // => 'I am zkk'

// 现在还没有武器,只会用拳头
player.fire()  // => 'I can only punch!'

// 哎,捡到一个手枪,装饰上
const playerWithPistol = new Pistol(player)

// 发现敌人,用手枪开火
playerWithPistol.fire()  // => 'I shoot with my Pistol!'

// 哇!捡到一个98K,装饰上
const playerWithKar98 = new Kar98(player)

// 用98k开火,奈斯!
playerWithKar98.fire() // => 'I shoot with my Kar98!'

ES7装饰器

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值