东城做网站,义乌来料123加工网,营销论坛网站建设,公司网站建设方案汇报定义
动态(组合)地给一个对象增加一些额外的职责。就增加功能而言#xff0c;Decorator模式比生成子类(继承)更为灵活(消除重复代码减少子类个数)。 一《设计模式》 GoF
装饰器模式#xff08;Decorator Pattern#xff09;允许向一个现有的对象添加新的功能#xf…定义
动态(组合)地给一个对象增加一些额外的职责。就增加功能而言Decorator模式比生成子类(继承)更为灵活(消除重复代码减少子类个数)。 一《设计模式》 GoF
装饰器模式Decorator Pattern允许向一个现有的对象添加新的功能同时又不改变其结构。这种类型的设计模式属于结构型模式它是作为现有的类的一个包装。装饰器模式通过将对象包装在装饰器类中以便动态地修改其行为。这种模式创建了一个装饰类用来包装原有的类并在保持类方法签名完整性的前提下提供了额外的功能。
使用场景
在某些情况下我们可能会“过度地使用继承来扩展对象的功能”由于继承为类型引入的静态特质使得这种扩展方式缺乏灵活性;并且随着子类的增多(扩展功能的增多)各种子类的组合(扩展功能的组合会导致更多子类的膨胀。如何使“对象功能的扩展能够根据需要来动态地实现?同时避免“扩展功能的增多带来的子类膨胀问题?从而使得任何“功能扩展变化所导致的影响将为最低?
结构 代码示例
//Decorator.h
/****************************************************/
#ifndef DECORATOR_H
#define DECORATOR_H
#includeiostream
using namespace std;//创建一个形状的接口
class shape
{
public:shape() {};virtual ~shape() {};virtual void draw()0;
};//创建圆形circle类继承形状基类接口
class circle :public shape
{
public:circle(){};~circle(){};void draw(){cout draw circle endl;}
};//创建一个三角形rectangle类继承形状shape基类
class rectangle :public shape
{
public:rectangle(){};~rectangle(){};void draw(){cout draw rectangle endl;}
};//创建一个形状装饰器ShapeDecorator类继承形状shape基类
class ShapeDecorator:public shape
{
public:ShapeDecorator(shape *td){decoratedshape td;}virtual ~ShapeDecorator(){};void draw(){decoratedshape-draw();}
protected:shape *decoratedshape;
};//扩展ShapeDecorator为RedShapeDecorator
class RedShapeDecorator : public ShapeDecorator
{
public:RedShapeDecorator(shape *tf):ShapeDecorator(tf){}~RedShapeDecorator(){};void draw(){decoratedshape-draw();setRedBorder(decoratedshape);}
private://设置边框颜色void setRedBorder(shape *tg){cout Border Color:Red endl;}
};#endif
//test.cpp
/****************************************************/
#include iostream
#include string
#include Decorator.hint main()
{shape *redCircle (shape*)new RedShapeDecorator(new circle());shape *redRectangle (shape*)new RedShapeDecorator(new rectangle());redCircle-draw();redRectangle-draw();delete redCircle;delete redRectangle;return 0;
}运行结果
要点总结
通过采用组合而非继承的手法Decorator模式实现了在运行时动态扩展对象功能的能力而且可以根据需要扩展多个功能。避免了使用继承带来的“灵活性差”和“多子类衍生问题”。Decorator类在接口上表现为is-a Component的继承关系即Decorator类继承了Component类所具有的接口。但在实现上又表现为has-a Component的组合关系即Decorator类又使用了另外一个Component类。Decorator模式的目的并非解决“多子类衍生的多继承”问题Decorator模式应用的要点在于解决“主体类在多个方向上的扩展功能”一是为“装饰”的含义。