装饰模式C++详解
裝飾模式
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: };#endifPerson.h實際的需要裝飾的對象
#ifndef PERSON_H_ #define PERSON_H_#include "Componet.h"class Person : public Componet {public:Person() {}~Person() {}void Show() { cout << "有一個人" << endl; }private: };#endifDecorate.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
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; } };#endifPants.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. 裝飾模式的缺點
- 會出現許多的裝飾邏輯類,使代碼變得復雜
總結
- 上一篇: ANTLR实践
- 下一篇: FlexSlider图片轮播切换jQue