裝飾器模式:
? ? ? ? ? ? 動態(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?