每日博客

装饰模式

本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:

1、理解装饰模式的动机,掌握该模式的结构;

2、能够利用装饰模式解决实际问题。

 

 

[实验任务一]:手机功能的升级

用装饰模式模拟手机功能的升级过程:简单的手机(SimplePhone)在接收来电时,会发出声音提醒主人;而JarPhone除了声音还能振动;更高级的手机(ComplexPhone)除了声音、振动外,还有灯光闪烁提示。

C++

#include <iostream>
#include <string>
#include <list>
using namespace std;

class Phone
{
public:
Phone() {}
virtual ~Phone() {}
virtual void ShowDecorate() {}
};
//具体的手机类
class NokiaPhone : public Phone
{
private:
string m_name;
public:
NokiaPhone(string name): m_name(name){}
~NokiaPhone() {}
void ShowDecorate() { cout<<m_name<<"在接收来电时:"<<endl;}
};
//装饰类
class DecoratorPhone : public Phone
{
private:
Phone *m_phone; //要装饰的手机
public:
DecoratorPhone(Phone *phone): m_phone(phone) {}
virtual void ShowDecorate() { m_phone->ShowDecorate(); }
};
//具体的装饰类
class DecoratorPhoneA : public DecoratorPhone
{
public:
DecoratorPhoneA(Phone *phone) : DecoratorPhone(phone) {}
void ShowDecorate() { DecoratorPhone::ShowDecorate(); AddDecorate(); }
private:
void AddDecorate() { cout<<"声音"<<endl; } //增加的装饰
};
//具体的装饰类
class DecoratorPhoneB : public DecoratorPhone
{
public:
DecoratorPhoneB(Phone *phone) : DecoratorPhone(phone) {}
void ShowDecorate() { DecoratorPhone::ShowDecorate(); AddDecorate(); }
private:
void AddDecorate() { cout<<"振动"<<endl; } //增加的装饰
};
//具体的装饰类
class DecoratorPhoneC : public DecoratorPhone
{
public:
DecoratorPhoneC(Phone *phone) : DecoratorPhone(phone) {}
void ShowDecorate() { DecoratorPhone::ShowDecorate(); AddDecorate(); }
private:
void AddDecorate() { cout<<"灯光闪烁"<<endl; } //增加的装饰
};
main()
{
Phone *iphone = new NokiaPhone("SimplePhone");
Phone *dpa = new DecoratorPhoneA(iphone);
dpa->ShowDecorate();

Phone *phone = new NokiaPhone("JarPhone");
Phone *dpA = new DecoratorPhoneA(phone);
Phone *dpb = new DecoratorPhoneB(dpA);
dpb->ShowDecorate();

Phone *cphone = new NokiaPhone("ComplexPhone");
Phone *d= new DecoratorPhoneA(cphone);
Phone *dpB = new DecoratorPhoneB(d);
Phone *dpC = new DecoratorPhoneC(dpB);
dpC->ShowDecorate();

delete dpa;
delete iphone;

delete dpA;
delete dpb;
delete phone;

delete d;
delete dpB;
delete dpC;
delete cphone;
}

posted @ 2021-10-25 21:04  谦寻  阅读(36)  评论(0编辑  收藏  举报