博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
设计模式(7) - Decorator装饰者模式
阅读量:4071 次
发布时间:2019-05-25

本文共 1567 字,大约阅读时间需要 5 分钟。

目录


1.意图

  动态地给一个对象加入额外的方法/行为。

  装饰者为它的子类提供了灵活的扩展方法/函数的行为。

2.UML类图

 

3.代码实现

#include
#include
using namespace std;//we are going to decorate a houseclass House{public: virtual void draw() = 0; virtual string getDescription() = 0; virtual ~House() {}};class SimpleHouse: public House{public: void draw() {} string getDescription() { return "simple house\n"; }};class HouseDecorator: public House{protected: House *decoratedHouse;public: HouseDecorator(House *hs):decoratedHouse(hs){}};//Indoorclass IndoorDecorator:public HouseDecorator{public: IndoorDecorator(House *hs):HouseDecorator(hs) {} void draw() { drawIndoor(); decoratedHouse->draw(); } string getDescription() { return decoratedHouse->getDescription() + "with Indoor\n"; }private: void drawIndoor(){ }};//Outdoorclass OutdoorDecorator: public HouseDecorator{public: OutdoorDecorator(House *hs):HouseDecorator(hs) { } void draw() { drawOutdoor(); decoratedHouse->draw(); } string getDescription() { return decoratedHouse->getDescription() + "with Outdoor\n"; }private: void drawOutdoor() {}};int main(){ House *hs=new SimpleHouse(); std::cout<
getDescription()<
getDescription()<
getDescription()<
getDescription()<

运行结果:

  simple house

  simple house

  with Indoor

  simple house

  with Outdoor

  simple house

  with Outdoor
  with Indoor

  分析:

  每一个component(House) 可以被它own或者wrapped装饰者使用。
  ConcreteComponent(SimpleHouse)就是我们即将对其动态地增加方法(Outdoor/Indoor)的对象,继承自House。
  每一个装饰者has-a(wraps) 一个componet,这意味着装饰者拥有一个指向House对象的指针(decoratedHouse成员)。

你可能感兴趣的文章
postgresql减少wal日志生成量的方法
查看>>
postgresql使用RHCS套件搭建HA高可用集群
查看>>
postgresql initdb过程中大体做了什么
查看>>
linux下的mysql源码安装
查看>>
plsql连接oracle出现ORA-12154: TNS: 无法解析指定的连接标识符
查看>>
oracle 查看库中每个表所占的空间大小
查看>>
流复制中的问题max_connection
查看>>
在mysql中使用模糊查询时,使用中文查询结果不正确问题
查看>>
redhat7修改系统语言
查看>>
启动rabbitmq:ERROR: distribution port 25672 in use on localhost (by non-Erlang process?)
查看>>
Linux下mysql8.0用rpm安装
查看>>
linux下mysql 8.0忘记密码后重置密码
查看>>
mysql学习笔记(一)
查看>>
mysql学习笔记(二)
查看>>
mysql学习笔记(三)
查看>>
mysql学习笔记(四)
查看>>
mysql学习笔记(五)
查看>>
mysql学习笔记(六)
查看>>
iOS 微信SDK1.8.6后需要UniversalLink解决方案及采坑记录
查看>>
iOS 异形tabBar, 中间item凸起
查看>>