(四)装饰模式-C++实现

时间:2023-03-09 09:17:25
(四)装饰模式-C++实现

动态地给对象添加一些额外的职责。就功能来说,装饰模式相比派生子类更为灵活。

当需要改进类的某个功能,而不是该类创建的全部对象时,可以使用这种设计模式。

装饰模式中有四种角色;

1、抽象组件:我们需要改进的类的父类,是一个抽象类。定义了一些虚函数。

2、具体组件:也就是它的某些对象可能需要被改进。也叫做被装饰者。

3、装饰:它也是抽象组件的子类,并且还包含一个抽象组件的声明,用来保存被装饰者的引用。它可以是抽象类,也可是是非抽象类。

4、具体装饰:它是装饰的实例。

本例实现的是一个Bird,作为一个抽象组件,即需要被改进的。有三个文件,Bird.h 和Bird.cpp以及测试用的decorator.cpp

实现如下;

1、Bird.h

 /*
抽象组件和具体组件的头文件声明
*/ #ifndef _BIRD_H_
#define _BIRD_H_ //抽象组件
class Bird{
public:
virtual int fly() = ; };
//具体组件(被装饰者)
class Sparrow : public Bird{
public:
int fly() override; //override代表它是重写的父类的虚函数
public:
const int DISTANCE = ;
}; //装饰者 也继承抽象组件 (即抽象组件即可以指向被装饰者,也可以指向装饰者)
class Decorator : public Bird{
public:
Decorator(){} Decorator(Bird* bird); protected:
Bird *myBird; //并且依赖抽组件
}; //具体装饰者
class SparrowDecorator : public Decorator{
public:
SparrowDecorator(Bird *bird);
int fly() override;
private:
int eleFly();
public:
const int DISTANCE = ; }; #endif

2、Bird.cpp

 #include "Bird.h"

 int Sparrow::fly()
{
return DISTANCE;
} Decorator::Decorator(Bird *bird)
{
myBird = bird;
} SparrowDecorator::SparrowDecorator(Bird *bird) :Decorator(bird)
{
} int SparrowDecorator::fly()
{
int distance = ;
distance = myBird->fly() + eleFly();
return distance;
} int SparrowDecorator::eleFly()
{
return DISTANCE;
}

3、decorator.cpp

 #include <iostream>
#include "Bird.h"
using namespace std; void needBird(Bird *bird)
{
int flyDistance = bird->fly();
cout << "this bird can fly " << flyDistance << "mile" << endl; } int main()
{
Bird *sparrow = new Sparrow(); //普通的鸟
Bird *sparrowDecorator1 = new SparrowDecorator(sparrow);
Bird *sparrowDecorator2 = new SparrowDecorator(sparrowDecorator1);
needBird(sparrowDecorator1);
needBird(sparrowDecorator2);
return ;
}

装饰模式最重要的就是,“具体组件”和“装饰”都是抽象组件的子类,说明抽象组件的对象声明即可以存放“被装饰者”的引用,也可以存放“装饰者的引用”,这样一个“被装饰者”被装饰变为“装饰者”之后,还可以被装饰,即多次装饰。