日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

C++设计模式-装饰模式

發布時間:2025/3/15 c/c++ 19 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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_H

Head.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++设计模式-装饰模式的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。