C++设计模式-装饰模式
生活随笔
收集整理的這篇文章主要介紹了
C++设计模式-装饰模式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
目錄
?
?
基本概念
代碼和實例
?
基本概念
裝飾模式是為已有功能動態地添加更多功能的一種方式。
當系統需要新功能的時候,是向舊系統的類中添加新代碼。這些新代碼通常裝飾了原有類的核心職責或主要行為。
?
裝飾模式的優點:
? ? ? ? ?1. 把類中的裝飾功能從類中搬移出去,這樣可以簡化原有的類;
? ? ? ? ?2. 有效地把類的核心職責和裝飾功能區分開了。而且可以去除相關類中重復的裝飾邏輯。
?
代碼和實例
結構圖如下(使用的大話設計模式的結構圖)
程序運行截圖如下:
代碼如下:
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是定義一個對象接口,可以給這些對象動態地添加職責。ConcreteComponent是定義一個具體的對象,也可以給這個對象添加一些職責。Decorator,裝飾抽象類,繼承了Component,從外類來擴展Component類的功能,但對Component來說,是無需知道Decorator的存在的,置于ConcreteDecorator是具體的裝飾對象,起到給Component添加職責的功能
總結
以上是生活随笔為你收集整理的C++设计模式-装饰模式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 软考系统架构师笔记-最后知识点总结(四)
- 下一篇: C++设计模式-抽象工厂模式