提交 46e47237 编写于 作者: L liu-jianhao

Decorator-Pattern Head first

上级 23e4f794
#ifndef BEVERAGE_HPP
#define BEVERAGE_HPP
#include <string>
class Beverage {
public:
virtual std::string getDescription() {
return "Unkown Beverage";
}
virtual double cost() = 0;
virtual ~Beverage() = default;
};
#endif
\ No newline at end of file
#ifndef CONDIMENTDECORATOR_HPP
#define CONDIMENTDECORATOR_HPP
#include "Beverage.hpp"
#include <memory>
class CondimentDecorator : public Beverage {
protected:
std::unique_ptr<Beverage> beverage;
public:
CondimentDecorator(std::unique_ptr<Beverage> b) : beverage(std::move(b)) {}
virtual ~CondimentDecorator() = default;
};
#endif
#ifndef ESPRESSO_HPP
#define ESPRESSO_HPP
#include "Beverage.hpp"
class Espresso : public Beverage {
public:
std::string getDescription() {
return "Espresso";
}
double cost() {
return 1.99;
}
};
#endif
\ No newline at end of file
#ifndef HOUSEBLEND_HPP
#define HOUSEBLEND_HPP
#include "Beverage.hpp"
class HouseBlend : public Beverage {
public:
std::string getDescription() {
return "House Blend Coffee";
}
double cost() {
return .89;
}
};
#endif
\ No newline at end of file
all:
g++ -g -Wall -o main main.cpp
rm:
main
\ No newline at end of file
#ifndef MOCHA_HPP
#define MOCHA_HPP
#include "CondimentDecorator.hpp"
class Mocha : public CondimentDecorator {
public:
Mocha(std::unique_ptr<Beverage> b) : CondimentDecorator(std::move(b)) {}
std::string getDescription() {
return beverage->getDescription() + ", Mocha";
}
double cost() {
return .20 + beverage->cost();
}
};
#endif
\ No newline at end of file
## 装饰者模式
![](https://img-blog.csdnimg.cn/20190610235715849.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlc3Ricm9va2xpdQ==,size_16,color_FFFFFF,t_70)
#include "Espresso.hpp"
#include "Mocha.hpp"
#include "HouseBlend.hpp"
#include <iostream>
int main() {
std::unique_ptr<Beverage> b2 = std::make_unique<Espresso>();
b2 = std::make_unique<Mocha>(std::move(b2));
std::cout << b2->getDescription() << " $" << b2->cost() << std::endl;
std::unique_ptr<Beverage> b3 = std::make_unique<HouseBlend>();
b3 = std::make_unique<Mocha>(std::move(b3));
std::cout << b3->getDescription() << " $" << b3->cost() << std::endl;
}
\ No newline at end of file
......@@ -47,6 +47,7 @@
+ [Strategy(Head-First版)](https://github.com/liu-jianhao/Cpp-Design-Patterns/tree/master/Strategy-Pattern)
### 单一职责:
+ [Decorator](https://github.com/liu-jianhao/Cpp-Design-Patterns/tree/master/Decorator)
+ [Decorator(Head-First版)](https://github.com/liu-jianhao/Cpp-Design-Patterns/tree/master/Decorator-Pattern)
+ [Bridge](https://github.com/liu-jianhao/Cpp-Design-Patterns/tree/master/Bridge)
### 对象创建:
+ [Factory Method](https://github.com/liu-jianhao/Cpp-Design-Patterns/tree/master/Factory%20Method)
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册