搜索

软件设计实验11


发布时间: 2022-11-24 17:39:01    浏览次数:10 次

实验11:装饰模式

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

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

直接放源码:

#include<iostream>
#include<string>
using namespace std;
class Phone{
public:virtual void receiveCall()=0;
};

class SimplePhone :public Phone{
public:void receiveCall(){
        cout << "接受来电,电话响了" << endl;
    }
};

class PhoneDecorator :public Phone{
private:Phone *pho;
public:PhoneDecorator(Phone *p){
        if (p != NULL){
            pho = p;
        }
        else{
            pho = new SimplePhone();

        }
    }
    void receiveCall(){
        pho->receiveCall();
    }
};
class JarPhone:public PhoneDecorator{
private:Phone *p;
public: JarPhone(Phone *p):PhoneDecorator(p) {
        // TODO Auto-generated constructor stub
        this->p = p;
    }
    void receiveCall(){
        p->receiveCall();
        cout<<"接受来电,手机震动"<<endl;
    }

};
class ComplexPhone :public PhoneDecorator{
private:Phone *p;
public: ComplexPhone(Phone *p) :PhoneDecorator(p) {
        // TODO Auto-generated constructor stub
        this->p = p;
    }
    void receiveCall(){
        p->receiveCall();
        cout << "接受来电,灯光闪烁" << endl;
    }

};
int main(){
    Phone *p = new SimplePhone();
    p->receiveCall();
    cout<<"Simple"<<endl;
    Phone *p1 = new JarPhone(p);
    p1->receiveCall();
    cout<<"JarPhone"<<endl;
    Phone *p2 = new ComplexPhone(p1);
    p2->receiveCall();
    cout<<"ComplexPhone"<<endl;
}

  

免责声明 软件设计实验11,资源类别:文本, 浏览次数:10 次, 文件大小:-- , 由本站蜘蛛搜索收录2022-11-24 05:39:01。此页面由程序自动采集,只作交流和学习使用,本站不储存任何资源文件,如有侵权内容请联系我们举报删除, 感谢您对本站的支持。 原文链接:https://www.cnblogs.com/lyf3701/p/16795744.html