C++设计模式-装饰模式
目錄
?
?
基本概念
代碼和實(shí)例
?
基本概念
裝飾模式是為已有功能動(dòng)態(tài)地添加更多功能的一種方式。
當(dāng)系統(tǒng)需要新功能的時(shí)候,是向舊系統(tǒng)的類中添加新代碼。這些新代碼通常裝飾了原有類的核心職責(zé)或主要行為。
?
裝飾模式的優(yōu)點(diǎn):
? ? ? ? ?1. 把類中的裝飾功能從類中搬移出去,這樣可以簡(jiǎn)化原有的類;
? ? ? ? ?2. 有效地把類的核心職責(zé)和裝飾功能區(qū)分開(kāi)了。而且可以去除相關(guān)類中重復(fù)的裝飾邏輯。
?
代碼和實(shí)例
結(jié)構(gòu)圖如下(使用的大話設(shè)計(jì)模式的結(jié)構(gòu)圖)
程序運(yùn)行截圖如下:
代碼如下:
Head.h
#ifndef HEAD_H #define HEAD_H#include <iostream> #include <string> using namespace std;class Component{public:virtual void Operation(){} };class ConcreteComponent: public Component{public:void Operation(); };class Decorator: public Component{public:Decorator();void setComponent(Component *component);void Operation();private:Component *m_component; };class ConcreteDecoratorA: public Decorator{public:ConcreteDecoratorA();void Operation();private:string m_state; };class ConcreteDecoratorB: public Decorator{public:void Operation(); };class ConcreteDecoratorC: public Decorator{public:void Operation(); };#endif // !HEAD_HHead.cpp
#include "Head.h"void ConcreteComponent::Operation() {cout << "基本框架" << endl; }Decorator::Decorator() {this->m_component = nullptr; }void Decorator::setComponent(Component *component) {this->m_component = component; }void Decorator::Operation() {if(this->m_component != nullptr){m_component->Operation();} }ConcreteDecoratorA::ConcreteDecoratorA() {m_state = "組建一"; }void ConcreteDecoratorA::Operation() {Decorator::Operation();cout << m_state << endl; }void ConcreteDecoratorB::Operation() {Decorator::Operation();cout << "組建二" << endl; }void ConcreteDecoratorC::Operation() {Decorator::Operation();cout << "組建三" << endl; }main.cpp
#include "Head.h"void main(void){ConcreteComponent *c1 = new ConcreteComponent;ConcreteDecoratorA *ccdA1 = new ConcreteDecoratorA;ConcreteDecoratorB *ccdB1 = new ConcreteDecoratorB;ccdA1->setComponent(c1);ccdB1->setComponent(ccdA1);ccdB1->Operation();delete c1;delete ccdB1;delete ccdA1;cout << endl;cout << "---------------華麗的分割線---------------" << endl;ConcreteComponent *c2 = new ConcreteComponent;ConcreteDecoratorA *ccdA2 = new ConcreteDecoratorA;ConcreteDecoratorC *ccdC2 = new ConcreteDecoratorC;ccdA2->setComponent(c2);ccdC2->setComponent(ccdA2);ccdC2->Operation();delete c2;delete ccdA2;delete ccdC2;getchar(); }?
Component是定義一個(gè)對(duì)象接口,可以給這些對(duì)象動(dòng)態(tài)地添加職責(zé)。ConcreteComponent是定義一個(gè)具體的對(duì)象,也可以給這個(gè)對(duì)象添加一些職責(zé)。Decorator,裝飾抽象類,繼承了Component,從外類來(lái)擴(kuò)展Component類的功能,但對(duì)Component來(lái)說(shuō),是無(wú)需知道Decorator的存在的,置于ConcreteDecorator是具體的裝飾對(duì)象,起到給Component添加職責(zé)的功能
總結(jié)
以上是生活随笔為你收集整理的C++设计模式-装饰模式的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 软考系统架构师笔记-最后知识点总结(四)
- 下一篇: C++设计模式-抽象工厂模式