装饰器模式

装饰器模式

            动态的给一个对象添加一些额外的职责 ,就增加功能来说,装饰模式比生成子类更灵活


land 类:  土地  要在土地上建房子

.h:

#ifndef LAND_H_

#define LAND_H_

class Land{

public:

Land();

~Land();

virtual int cost(){};

};

.cpp

这里就是写俩个空的构造和析构


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 

你可能感兴趣的:(装饰器模式)