装饰者模式例子

c10.h
#include <string>

class Beverage {
public:
        virtual std::string getDescription() = 0;
        virtual double cost() = 0;
};

class Soy: public Beverage {
private:
        Beverage* beverage; // 把传进来的被装饰者赋给它,以便调用被装饰者的函数
public:
        Soy(Beverage* beverage); // 构造对象时传进被装饰者
        double cost();
        std::string getDescription();
};

class Mocha: public Beverage {
private:
        Beverage* beverage;
public:
        Mocha(Beverage* beverage);
        double cost();
        std::string getDescription();
};

class Milk: public Beverage {
private:
        Beverage* beverage;
        Milk(Beverage* beverage);
        double cost();
        std::string getDescription();
};

class Beverage1: public Beverage {
public:
        std::string getDescription();
        double cost();
};
c10.cc

#include "c10.h"
#include <string>
#include <stdio.h>

std::string Soy::getDescription() {
        return beverage->getDescription() += "Soy";
}

double Soy::cost() {
        return beverage->cost() + 10.5;
}

Soy::Soy(Beverage* beverage) {
        this->beverage = beverage;
}

std::string Mocha::getDescription() {
        return beverage->getDescription() += "Mocha";
}

double Mocha::cost() {
        return beverage->cost() + 20.5;
}

Mocha::Mocha(Beverage* beverage) {
        this->beverage = beverage;
}

std::string Beverage1::getDescription() {
        return "beverage1";
}

double Beverage1::cost() {
        return 10;
}

Milk::Milk(Beverage* beverage) {
        this->beverage = beverage;
}

std::string Milk::getDescription() {
        return beverage->getDescription() += "Milk";
}

double Milk::cost() {
        return 5.1;
}

int main() {
        Beverage* b1 = new Beverage1;
        b1 = new Soy(b1);
        b1 = new Mocha(b1);
        printf("%s is $%0.1f\n", (b1->getDescription()).c_str(), b1->cost());
        return 0;
}
据说JAVA的IO库有多得使人眼花缭乱的类就是因为使用了这个模式,让你可以一个一个功能的叠加上去。以前一开始接触编程的时候除C外就是看JAVA,当看到有如此多的类和函数且名字又是如此相似的时候确实困惑了,有必要为了加那么一点功能来实现多一个类么!!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值