生活随笔
收集整理的這篇文章主要介紹了
设计模式复习-装饰模式
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1.?Component是定義一個(gè)對(duì)象接口,可以給這些對(duì)象動(dòng)態(tài)地添加職責(zé)。ConcreteComponent是定義一個(gè)具體的對(duì)象,也可以給這個(gè)對(duì)象添加一些職責(zé)。Decorator,裝飾抽象類(lèi),繼承了Component,從外類(lèi)來(lái)擴(kuò)展Component類(lèi)的功能,但對(duì)于Component來(lái)說(shuō),是無(wú)需知道Decorator的存在的。至于ConcreteComponent就是具體的裝飾對(duì)象,起到給Component添加職責(zé)的功能。
?
2.?裝飾模式是利用SetComponent來(lái)對(duì)對(duì)象進(jìn)行包裝的。這樣每個(gè)裝飾對(duì)象的實(shí)現(xiàn)就和如何使用這個(gè)對(duì)象分離開(kāi)了,每個(gè)裝飾對(duì)象只關(guān)心自己的功能,不需要關(guān)心如何被添加到對(duì)象鏈中。
3.?如果只有一個(gè)ConcreteComponent類(lèi)而沒(méi)有抽象的Component類(lèi),那么Decorator類(lèi)可以是ConcreteComponent的一個(gè)子類(lèi),同樣道理,如果只有一個(gè)ConcreteDecorator類(lèi),那么就沒(méi)有必要建立一個(gè)單獨(dú)的Decorator類(lèi),而可以把Decorator和ConcreteDecorator的責(zé)任合并成一個(gè)類(lèi)。
代碼:
#pragma once
#include "stdafx.h"
#include<iostream>
#include<windows.h>
using namespace std;class Component {
public:virtual VOID Operator() = 0;
};class ConcreteComponent :public Component {
public:VOID Operator() {cout << "具體操作對(duì)象" << endl;}
};class Decorator :public Component {
private:Component * mpComponent = NULL;
public:VOID SetComponent(Component * pComponent) {mpComponent = pComponent;}VOID Operator() {if (mpComponent != NULL) {mpComponent->Operator();}}
};class ConcreteDecoratorA :public Decorator {
public:VOID Operator() {Decorator::Operator();cout << "具體裝飾對(duì)象A的操作" << endl;}
};class ConcreteDecoratorB :public Decorator {
public:VOID Operator() {Decorator::Operator();cout << "具體裝飾對(duì)象B的操作" << endl;}
};int main()
{ConcreteComponent *pPeople = new ConcreteComponent(); //定義一個(gè)人ConcreteDecoratorA *pClothesA = new ConcreteDecoratorA();//A衣服ConcreteDecoratorB *pClothesB = new ConcreteDecoratorB();//B衣服pClothesA->SetComponent(pPeople); //穿A衣服pClothesB->SetComponent(pClothesA);//繼續(xù)穿上B衣服pClothesB->Operator(); //showtimedelete pPeople, delete pClothesA, delete pClothesB;getchar();return 0;
}
?
總結(jié)
以上是生活随笔為你收集整理的设计模式复习-装饰模式的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。