php装饰器模式 简书,设计模式(四)-装饰器模式

装饰器模式

允许将一个现有对象添加新的功能,同时又不改变其结构,这种类型的设计模式属于结构型模式,它作为现有类的一个包装,并且保持类的完整性的前提下,提供额外的功能.

图例

0b9b93d20171

image.png

代码实现

class Coffee{

make(water){

return `咖啡:加${water}`

}

}

class MileCoffee{

constructor(parent){

this.parent=parent

}

make(water){

return `${this.parent.make(water)}加奶`

}

}

class SugarCoffee{

constructor(parent){

this.parent=parent

}

make(water){

return `${this.parent.make(water)}加糖`

}

}

let coffee=new Coffee()

let mileCoffee=new MileCoffee(coffee);

let sugarCoffee=new SugarCoffee(mileCoffee);

console.log(sugarCoffee.make('水')) //咖啡:加水加奶加糖

AOP(Aspect Oriented Programming)切片编程

针对业务处理过程中的切面进行提取,它所面对的是处理过程中的某个步骤或阶段,将逻辑过程中各部分之间低耦合的隔离效果.

代码实现

// before-target-after

Function.prototype.before=function(beforeFunc){

let _this=this; //function buy

return function(){

beforeFunc.apply(this,arguments)

_this.apply(this,arguments)

}

}

Function.prototype.after=function(afterFunc){

let _this=this;

return function(){

_this.apply(this,arguments);

afterFunc.apply(this,arguments)

}

}

function buy(money,goods){

console.log(`花了${money}钱,买了${goods}`)

}

buy=buy.before(function(){

console.log(`像媳妇要了1元钱`)

})

buy=buy.after(function(){

console.log(`退还媳妇0.2元钱`)

})

buy(0.8,'盐')

//像媳妇要了1元钱

//花了0.8钱,买了盐

//退还媳妇0.2元钱

应用场景

//vue mixin

const toggle = {

data() {

return {

isShowing: false

}

},

methods: {

toggleShow() {

this.isShowing = !this.isShowing;

}

}

}

const Modal = {

template: '#modal',

mixins: [toggle],

components: {

appChild: Child

}

};

const Tooltip = {

template: '#tooltip',

mixins: [toggle],

components: {

appChild: Child

}

};

优点

1.可维护性高:可以替代传统类的继承方式来实现功能的拓展,减少子类的数量,允许用户在不引起子类数量暴增的前提下动态的修饰对象.添加功能.

2.灵活性高:被装饰可以使用装饰器动态的添加和撤销功能.

3.复用性高:可以将一个功能装饰器用来装饰不同的类型对象,实现装饰器的复用.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值