2024.11.7(周四)

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

实验要求:

1.提交类图;

2.提交源代码;

3.注意编程规范。

 

1、类图

 

 

2、源代码

#include <iostream>

#include <string>

#include <list>

using namespace std;

 

class Phone

{

public:

    Phone() {}

    virtual ~Phone() {}

    virtual void ShowDecorate() {}

};

 

// 具体的手机类

class SimplePhone : public Phone

{

private:

    string namePhone;

 

public:

    SimplePhone(string name) : namePhone(name) {}

    ~SimplePhone() {}

    void ShowDecorate()

    {

        cout << endl << namePhone << ":" << 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; } // 增加的装饰

};

 

int main()

{

    Phone* iphone = new SimplePhone("SimplePhone");

    Phone* dpa = new DecoratorPhoneA(iphone);

    dpa->ShowDecorate();

 

    Phone* phone = new SimplePhone("JarPhone");

    Phone* dpA = new DecoratorPhoneA(phone);

    Phone* dpb = new DecoratorPhoneB(dpA);

    dpb->ShowDecorate();

 

    Phone* cphone = new SimplePhone("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 @ 2024-11-11 07:55  记得关月亮  阅读(7)  评论(0)    收藏  举报