序、设计模式分类
一、装饰者模式(原型链)
二、策略模式
三、代理模式
四、发布订阅模式
五、迭代器模式
六、工厂模式
七、外观模式
八、状态模式
九、单例模式
十、适配器模式
参考:
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!'