設計模式 裝飾器模式

2021-09-26 15:56:50 字數 1692 閱讀 7576

適用場景

例項分析:

1、建立構件(定義飲料基類,提供名稱和價錢)

#ifndef __component_h_

#define __component_h_

#includeusing namespace std;

//飲料基類

class ibeverage

;#endif //component_h

2、建立具體構件(如有兩款咖啡:黑咖啡和烘焙咖啡)

//concrete_component.h

#ifndef __concrete_component_h__

#define __concrete_component_h__

#include "component.h"

//***具體的飲料(咖啡)類

//黑咖啡

class houseblend : public ibeverage

double cost()

};//烘焙咖啡

class darkroast: public ibeverage

double cost()

};#endif //concrete_component_h

#ifndef __decorator_h__

#define __decorator_h__

#include "component.h"

//調味品

class condimentdecorator : public ibeverage

string name()

double cost()

//note:是保護成員,不能是private,否則子類無法使用

protected:

ibeverage* m_pbeverage;

};#endif //decorator_h

#ifndef __concrete_decorator_h__

#define __concrete_decorator_h__

#include "decorator.h"

//奶油(調味品)

class cream : public condimentdecorator

string name()

double cost()

};//摩卡

class mocha : public condimentdecorator

string name()

double cost()

};//糖漿

class syrup : public condimentdecorator

string name()

double cost()

};#endif //concrete_decorator_h

#include#include "concrete_component.h"

#include "concrete_decorator.h"

#ifndef safe_delete

#define safe_delete(p)

#endif

int main()

設計模式 裝飾器模式

裝飾器模式 decorator pattern 允許向乙個現有的物件新增新的功能,同時又不改變其結構。這種型別的設計模式屬於結構型模式,它是作為現有的類的乙個包裝。這種模式建立了乙個裝飾類,用來包裝原有的類,並在保持類方法簽名完整性的前提下,提供了額外的功能。public inte ce playe...

設計模式 裝飾器模式

裝飾者模式的應用場景 裝飾者模式 decorator pattern 是指在不改變原有物件的基礎之上,將功能附加到物件上,提供了比繼承更有彈性的替代方案 擴充套件原有物件的功能 屬於結構型模式。裝飾者模式在我們生活中應用也比較多如給煎餅加雞蛋 給蛋糕加上一些水果 給房子裝修等,為物件擴充套件一些額外...

設計模式 裝飾器模式

定義 裝飾模式可以動態的給乙個物件增加一些額外的功能 增強功能 相比於繼承,裝飾模式能對不支援繼承的類進行增強 並且比繼承更靈活,不需要生成大量的子類。角色 實現 public abstract class house public abstract void sleep public class ...