Java/C++实现装饰模式---模拟手机功能的升级过程

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

类图:

Java代码:

public class Changer implements Phone{

    private Phone phone;
    public Changer(Phone p) {
        this.phone=p;
    }
    public void voice() {
        phone.voice();
    }
}

public class ComplexPhone extends Changer{

    public ComplexPhone(Phone p) {
        super(p);
        System.out.println("ComplexPhone");
    }

    public void zhendong() {
        System.out.println("会震动!");
    }
    public void dengguang() {
        System.out.println("会发光!");
    }

}


public class JarPhone extends Changer{

    public JarPhone(Phone p) {
        super(p);
        System.out.println("Jarphone");
    }

    public void zhendong() {
        System.out.println("会震动!");
    }
}

public interface Phone {
    public void voice();
}

public class SimplePhone implements Phone{

     public void voice() {
            System.out.println("发出声音!");
        }

}

public class Client {
    public static void main(String[] args) {
        Phone phone;
        phone=new SimplePhone();
        phone.voice();
        JarPhone jarphone=new JarPhone(phone);
        jarphone.voice();
        jarphone.zhendong();
        ComplexPhone complexphone = new ComplexPhone(phone);
        complexphone.zhendong();
        complexphone.dengguang();
    }
}

C++代码:

#include <iostream>
using namespace std;

class Phone
{
public:
    virtual void receiveCall(){};
};

class SimplePhone:public Phone
{
public:
    virtual void receiveCall(){
        cout<<"发出声音!"<<endl;
    }
};


class PhoneDecorator:public Phone {
protected:
    Phone *phone;

public:
    PhoneDecorator(Phone *p)
    {
        phone=p;
    }
    virtual void receiveCall()
    {
        phone->receiveCall();
    }
};


class JarPhone:public PhoneDecorator{
public:
    JarPhone(Phone *p):PhoneDecorator(p){}
    void receiveCall()
    {
        phone->receiveCall();
        cout<<"会震动!"<<endl;
    }
};

class ComplexPhone:public PhoneDecorator{
public:
    ComplexPhone(Phone *p):PhoneDecorator(p){}
    void receiveCall()
    {
        phone->receiveCall();
        cout<<"会发光!"<<endl;
    }
};

int main()
{
    Phone *p1=new SimplePhone();
    p1->receiveCall();
    cout<<"Jarphone"<<endl;
    Phone *p2=new JarPhone(p1);
    p2->receiveCall();
    cout<<"ComplexPhone"<<endl;
    Phone *p3=new ComplexPhone(p2);
    p3->receiveCall();
    return 0;
}

运行结果:

 

 

posted @ 2021-12-14 12:42  睡觉不困  阅读(287)  评论(0)    收藏  举报