装饰器设计模式就是在原有类的基础上增加一些装饰功能,顶层的接口实现子类作为要实例化的对象,传到装饰器中,增加特定装饰器的功能,我习惯用代码解释,直接看代码.
这段代码包含了两个例子,都是先定义一个顶层的接口,然后定义装饰器抽象类,里面维护了一个接口的指针,在具体的装饰器中,通过构造函数传递顶层接口的实现子类指针,借助多态机制实现装饰功能.
#include <bits/stdc++.h>
using namespace std;
/**----------------------------------------------------**/
class Cake {
public:
virtual void showCake() = 0;
virtual ~Cake(){};
std::string name;
};
class ConcreteCake : public Cake {
public:
ConcreteCake()
{
name = "原始蛋糕";
}
void showCake() { std::cout << name.c_str() << std::endl; };
virtual ~ConcreteCake(){};
};
class CakeDecrator : public Cake {
protected:
Cake* pCake; //维护一个Cake对象的引用,为Cake对象添加装饰
public:
virtual void showCake() = 0;
virtual ~CakeDecrator(){};
};
class CakeDecratorCholate : public CakeDecrator {
public:
CakeDecratorCholate(Cake* pCake)
{
this->pCake = pCake;
}
void showCake()
{
this->name = pCake->name + "加巧克力";
std::cout << name.c_str() << std::endl;
}
virtual ~CakeDecratorCholate(){};
};
/**-----------------------------------------------------------------------**/
class Shape {
public:
virtual void draw() = 0;
virtual ~Shape(){}
string name;
};
class Circle : public Shape {
public:
Circle()
{
this->name = "circle";
}
void draw() override
{
cout << this->name << endl;
}
virtual ~Circle()
{
}
};
class Decorator : public Shape {
public:
virtual void draw() = 0;
virtual ~Decorator()
{
}
Shape* shape;
};
class RedDecorator : public Decorator {
public:
RedDecorator(Shape* s)
{
//this->name = s->name + " red";
shape = s;
}
void draw()
{
this->name = shape->name + " red";
cout << this->name << endl;
}
virtual ~RedDecorator() {}
};
int main()
{
// Circle* circle = new Circle;
// circle->draw();
//RedDecorator* redCircle = new RedDecorator(circle);
//redCircle->draw();
ConcreteCake* cake = new ConcreteCake();
CakeDecratorCholate* cholateCake = new CakeDecratorCholate(cake);
cholateCake->showCake();
shared_ptr<Shape> circle(new Circle);
//Shape* circle = new Circle;
RedDecorator* redCircle = new RedDecorator(circle.get());
redCircle->draw();
}