设计模式-装饰器模式

/*装饰器模式:动态地扩展一个类的功能,是继承的替代模式,装饰类和被装饰类独立发展,不会相互耦合*/
#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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值