1. 程式人生 > 其它 >Java/C++實現裝飾模式---模擬手機功能的升級過程

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

執行結果: