软件设计实验11

实验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;
}

  

posted @ 2022-10-16 10:32  Lindseyyip  阅读(18)  评论(0编辑  收藏  举报