装饰模式
1. 装饰模式的作用
动态的给一个对象添一些额外的职责,就增加功能而言,装饰模式比生成子类更加的灵活。
为已有的功能动态的添加更多功能的一种方式
可以将勒种的核心职责和装饰从勒种移除,有效把职责和装饰分离
2. 装饰模式C++代码实现
3. 代码实现
Compont.h
#ifndef COMPONET_H_
#define COMPONET_H_
#include <iostream>
using namespace std;
class Componet {
public:
Componet() {}
~Componet() {}
virtual void Show(){}
private:
};
#endif
Person.h
实际的需要装饰的对象
#ifndef PERSON_H_
#define PERSON_H_
#include "Componet.h"
class Person : public Componet {
public:
Person() {}
~Person() {}
void Show() { cout << "有一个人" << endl; }
private:
};
#endif
Decorate.h
抽象装饰类
#ifndef DECORATE_H_
#define DECORATE_H_
#include "Componet.h"
class Decorate : public Componet {
public:
Decorate() {}
~Decorate() {}
void Show() { componet_->Show(); }
void decorate(Componet* c) { componet_ = c; }
protected:
Componet* componet_;
private:
};
#endif
接下来是具体的装饰对象Shirt.h
#ifndef SHIRT_H_
#define SHIRT_H_
#include "Decorate.h"
class Shirt : public Decorate {
public:
void Show() {
componet_->Show();
AddBehavior();
}
private:
void AddBehavior() { cout << "穿了一件衬衫" << endl; }
private:
};
#endif
Hat.h
#ifndef HAT_H_
#define HAT_H_
#include "Decorate.h"
class Hat : public Decorate {
public:
void Show() {
componet_->Show();
AddBehavior();
}
private:
void AddBehavior() { cout << "带上帽子" << endl; }
};
#endif
Pants.h
#ifndef PANTS_H_
#define PANTS_H_
#include "Decorate.h"
class Pants : public Decorate {
public:
void Show() {
componet_->Show();
AddBehavior();
}
private:
void AddBehavior() { cout << "穿上裤子" << endl; }
};
#endif
这就是一个递归调用的过程,跟俄罗斯套娃似得,利用虚函数的动态多态的机制,让componet_
指向不同的实际Decorate
main.cc
#include "Componet.h"
#include "Hat.h"
#include "Pants.h"
#include "Person.h"
#include "Shirt.h"
int main() {
Componet* man = new Person();
Shirt* shirt = new Shirt();
Pants* pants = new Pants();
Hat* hat = new Hat();
hat->decorate(man);
shirt->decorate(hat);
pants->decorate(shirt);
pants->Show();
}
输出的结果
有一个人
带上帽子
穿了一件衬衫
穿上裤子
4. 装饰模式的缺点
- 会出现许多的装饰逻辑类,使代码变得复杂