Design Pattern 设计模式 Decorator 装饰者模式
来源:互联网 发布:linux服务器root密码 编辑:程序博客网 时间:2024/06/06 07:07
1 设计一个基类
2 继承这个基类,并包含这个基类的一个对象
3 创建继承类的时候,初始化这个基类,因为是基类指针,所以可以是所有基类的衍生类对象,那么就可以叠加任意多个衍生类对象了。
关键是在衍生类中包含一个基类对象,然后有了继承和包含两重关系,可以使得一个类一个类对象叠加,达到装饰目的。
等于是创建了一个对象指针链表,一个一个对象发挥其相应的作用。
下面程序装饰一个桌子,同时包含释放内存的处理。
关键要知道基类的析构函数必须使用虚函数,为什么?
1 如果基类不是析构函数,那么如果衍生类中包含了动态分配地址,那么使用基类指针指向衍生类的时候,就无法正确释放内存了。
2 即使衍生类没有动态释放分配地址,那么增加个virtual也没坏处
#pragma once#include <string>#include <iostream>using namespace std;//base classclass Desk{public:virtual string description(){return "This is a Desk";}virtual ~Desk() {cout<<endl<<"delete Desk"<<endl;}//这里不使用virtual就无法正确释放内存,所有基类都应该使用virtual};//derived classclass ANiceLamp : public Desk{Desk *dk;public:ANiceLamp(Desk *d){if (dk) delete dk;//这句显得有点多余,因为一个对象只会创建一次dk = d;}string description(){return dk->description() + " with A Nice Lamp";}~ANiceLamp(){if (dk) delete dk;cout<<endl<<"Delete Lamp"<<endl;}};class Computer : public Desk{Desk * dk;public:Computer(Desk * d){if (dk) delete dk;dk = d;}string description(){return dk->description() + " with the best computer";}~Computer(){if (dk) delete dk;cout<<endl<<"delete Computer"<<endl;}};class Flower : public Desk{Desk *dk;public:Flower(Desk *d){if (dk) delete dk;dk = d;}string description(){return dk->description() + " with the most beautiful flower";}~Flower(){if (dk) delete dk;cout<<endl<<"delete Flower\n";}};void Decorator3DeskRun(){Desk *desk = new Desk();cout<<desk->description()<<std::endl;desk = new ANiceLamp(desk);cout<<desk->description()<<std::endl;desk = new Computer(desk);cout<<desk->description()<<std::endl;desk = new Flower(desk);cout<<desk->description()<<std::endl;desk = new Computer(desk);cout<<desk->description()<<std::endl;desk = new Flower(desk);cout<<desk->description()<<std::endl;delete desk;}
2 0
- Design Pattern 设计模式 Decorator 装饰者模式
- 装饰设计模式(decorator design pattern)
- 设计模式-装饰者模式(Decorator Pattern)
- 设计模式2--装饰模式(the decorator design pattern)
- 装饰设计模式 Learn Decorator Design Pattern in Easy Steps
- 7.5.1.2 装饰设计模式(THE DECORATOR DESIGN PATTERN)
- 装饰者设计模式(Decorator Pattern)
- 设计模式[6] Decorator Pattern 装饰模式
- 设计模式-装饰模式(Decorator Pattern)
- 设计模式之装饰模式(Decorator Pattern)
- 设计模式心得:装饰模式 (decorator pattern)
- 设计模式-装饰模式(Decorator Pattern)
- 设计模式之装饰模式--- Pattern Decorator
- 设计模式_装饰模式(Decorator Pattern)
- 设计模式【装饰模式Decorator Pattern】
- Decorator Pattern (装饰者模式)
- 装饰者模式(Decorator Pattern)
- 装饰者模式(decorator pattern)
- tomcat开启与配置ssi(支持动态引入html)
- 内核调试神器SystemTap — 更多功能与原理(三)
- HDU 1312 Red and Black(简单BFS)
- git stash和git stash pop
- oracle 执行大量的sql语句
- Design Pattern 设计模式 Decorator 装饰者模式
- web UI工程师必读的一篇文档,写的非常好
- 关于C语言等高级语言能不能直接控制硬件的问题
- quick-cocos2d-x 在 Windows 下的编译环境
- 安装scipy和numpy还有matplotlib
- 台媒:鸿海将代工苹果5.5寸iPhone
- Li Na really made a big upset,
- 继承者的难题:李在镕能否接班三星?
- 今日作息及食谱(5.28)