裝飾器模式

裝飾器模式

? ? ? ? ? ? 動態(tài)的給一個對象添加一些額外的職責 ,就增加功能來說,裝飾模式比生成子類更靈活


land 類:? 土地? 要在土地上建房子

.h:

#ifndef LAND_H_

#define LAND_H_

class Land{

public:

Land();

~Land();

virtual int cost(){};

};

.cpp

這里就是寫倆個空的構(gòu)造和析構(gòu)


room類

.h

#include "land.h"

#ifndef ROOM_H_

#define ROOM_H_

class Room : public Land

{

private :

int money =1000;? //基本空房間費用 1000

public :

Room();

~Room();

int cost();

};


.cpp

#include "Room.h"

Room::Room()

{

}

Room::~Room()

{

}

int Room::cost()

{

return this->money;

}

RoomDecorator 房間裝飾類 。

.h:

#include "land.h"

#ifndef ROOMDECORATOR_H_

#define ROOMDECORATOR_H_

class RoomDecorator : public Land

{

protected :

Land *land;

public:

RoomDecorator(Land * getPara);

~RoomDecorator();

};

.cpp

#include "RoomDecorator.h"

#include? "land.h"

RoomDecorator::RoomDecorator(Land * getPara)

{

this->land = getPara;

}

RoomDecorator::~RoomDecorator(){

}


DIngingRoom 廚房類 具體的房間裝飾

.h

#include "RoomDecorator.h"

#ifndef DINGINGROOM_H_

#define DINGINGROOM_H_

class DingingRoom : public RoomDecorator

{

public:

int cost();

};

#endif /* DINGINGROOM_H_ */

.cpp

#include "DingingRoom.h"

int DingingRoom::cost(){

return this->land->cost()+100;

}


LivingRoom 客廳類 具體裝飾類:

.h

#include "RoomDecorator.h"

#ifndef LIVINGROOM_H_

#define LIVINGROOM_H_

class LivingRoom : public RoomDecorator

{

public:

int cost();

};

#endif /* LIVINGROOM_H_ */


.cpp

#include "LivingRoom.h"

int LivingRoom::cost(){

return this->land->cost()+200;

}


通過一層一層的裝飾:

DingingRoom *livingDing = new DingingRoom (new LivingRoom(new Room()));

livingDing->cost();

得到話費1300?

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

  • 裝飾模式是以對客戶透明的方式動態(tài)地給一個對象附加上更多的職責。這也就是說,客戶端并不會覺得對象在裝飾前和裝飾后有什...
    flamez57閱讀 474評論 0 1
  • 0x01 前言 在編碼的時候,我們?yōu)榱藬U展一個類常用的方法就是繼承,隨著擴展功能越來越多,子類會變得越來越膨脹,使...
    天若有情天亦老閱讀 212評論 0 2
  • 本文源碼見:https://github.com/get-set/get-designpatterns/tree/...
    享學IT閱讀 341評論 0 0
  • 裝飾器模式可以在不修改代碼的情況下靈活的為一對象添加行為和職責。當你要修改一個被其它類包含的類的行為時,它可以代替...
    泥孩兒0107閱讀 353評論 0 0
  • 在前面相信大家對組合模式已經(jīng)有了一定的了解,現(xiàn)在我們來繼續(xù)講一下裝飾器模式。 什么是裝飾器模式 裝飾模式是通過組合...
    ManyHong閱讀 511評論 0 1

友情鏈接更多精彩內(nèi)容