装饰器模式

装饰器模式

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


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 

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 装饰模式是以对客户透明的方式动态地给一个对象附加上更多的职责。这也就是说,客户端并不会觉得对象在装饰前和装饰后有什...
    flamez57阅读 436评论 0 1
  • 0x01 前言 在编码的时候,我们为了扩展一个类常用的方法就是继承,随着扩展功能越来越多,子类会变得越来越膨胀,使...
    天若有情天亦老阅读 185评论 0 2
  • 本文源码见:https://github.com/get-set/get-designpatterns/tree/...
    享学IT阅读 317评论 0 0
  • 装饰器模式可以在不修改代码的情况下灵活的为一对象添加行为和职责。当你要修改一个被其它类包含的类的行为时,它可以代替...
    泥孩儿0107阅读 305评论 0 0
  • 在前面相信大家对组合模式已经有了一定的了解,现在我们来继续讲一下装饰器模式。 什么是装饰器模式 装饰模式是通过组合...
    ManyHong阅读 484评论 0 1