javascript设计模式之装饰者模式

在传统的面向对象的语言中,给对象添加功能常常使用继承的方式,但是继承方式并不灵活,还会带来许多问题:
一方面会导致超类和子类之间存在强耦合性,当超类改变时,子类也会随之改变;另一方面,继承这种功能通常被称为"白箱复用",在


class Beverage {
    constructor(description = "Unknown beverage") {
        this.description = description;
    }

    getDescription() {
        return this.description;
    }

    cost() {
        throw new Error("This method must be overwritten!");
    }
}

class CondimentDecorator extends Beverage {}

class Espresso extends Beverage {
    cost() {
        return 1.99;
    }
}

class HouseBlend extends Beverage {
    cost() {
        return 0.89;
    }
}

class Mocha extends CondimentDecorator {
    constructor(beverage) {
        super();
        this.beverage = beverage;
    }

    getDescription() {
        return this.beverage.getDescription() + ", Mocha";
    }

    cost() {
        return 0.2 + this.beverage.cost();
    }
}

class Whip extends CondimentDecorator {
    constructor(beverage) {
        super();
        this.beverage = beverage;
    }

    getDescription() {
        return this.beverage.getDescription() + ", Whip";
    }

    cost() {
        return 0.6 + this.beverage.cost();
    }
}

let oEspressoWithMochaAndWhip = new Espresso();
oEspressoWithMochaAndWhip = new Mocha(oEspressoWithMochaAndWhip);
oEspressoWithMochaAndWhip = new Whip(oEspressoWithMochaAndWhip);

console.log(oEspressoWithMochaAndWhip.cost());
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值