/*装饰器模式:动态地扩展一个类的功能,是继承的替代模式,装饰类和被装饰类独立发展,不会相互耦合*/
#include<iostream>
#include<string>
using namespace std;
class Shape
{
public:
virtual void draw() = 0;
virtual ~Shape(){}
};
class Circle : public Shape
{
public:
void draw(){cout<<"Circle shape."<<endl;}
};
class Rectangle : public Shape
{
public:
void draw(){cout<<"Rectangle shape."<<endl;}
};
class ShapeDecorator : public Shape //装饰类基类,继承Shape
{
public:
ShapeDecorator(Shape* s) : shape(s){}
virtual ~ShapeDecorator(){}
protected: //protected,子类能访问
Shape* shape; //将要被装饰的类嵌入装饰类中,由装饰类ShapeDecorator添加功能
};
class CorlorShape : public ShapeDecorator
{
public:
CorlorShape(Shape* s,const string& c) : ShapeDecorator(s),corlor(c){}
void draw()
{
shape->draw();
drawCorlor(); //添加的功能
}
private:
void drawCorlor()
{
cout<<"Draw corlor:"<<corlor<<endl;
}
string corlor;
};
class SizeShape : public ShapeDecorator
{
public:
SizeShape(Shape* s) : ShapeDecorator(s){}
void draw()
{
shape->draw();
size(); //添加的功能
}
private:
void size()
{
cout<<"Change size."<<endl;
}
};
int main()
{
Shape* circle = new Circle();
Shape* redCircle = new CorlorShape(circle,"yellow");
Shape* sizeCircle = new SizeShape(redCircle);
redCircle->draw();
sizeCircle->draw();
delete circle;
delete redCircle;
delete sizeCircle;
return 0;
}
设计模式-装饰器模式
最新推荐文章于 2024-09-23 11:02:24 发布