适配器模式

软件设计                  石家庄铁道大学信息学院

 

实验8:适配器模式

本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:

1、理解适配器模式的动机,掌握该模式的结构;

2、能够利用适配器模式解决实际问题

 

[实验任务一]:双向适配器

实现一个双向适配器,使得猫可以学狗叫,狗可以学猫抓老鼠。

实验要求:

1. 画出对应的类图;

 

2.提交源代码;

#include<iostream>

using namespace std;

class Cat{

public:

    virtual void miao()=0;

    virtual void catchs()=0;

};

class Dog{

public:

    virtual void wang()=0;

    virtual void run()=0;

};

class RealCat:public Cat{

public:

    void miao(){

        cout<<"喵喵叫!"<<endl;

    }

    void catchs(){

        cout<<"抓老鼠!"<<endl;

    }

};

class RealDog:public Dog{

public:

    void wang(){

        cout<<"汪汪叫!"<<endl;

    }

    void run(){

        cout<<"跑跑跑!"<<endl;

    }

};

class Adapter:public Cat,public Dog{

private:

    static Cat *cat;

    static Dog *dog;

public:

    void setCat(Cat *c){

        cat=c;

    }

    void setDog(Dog *d){

        dog=d;

    }

    void wang(){

    }

    void catchs(){

    }

    void run(){

        cout<<"小狗学小猫!"<<endl;

        cat->catchs();

    }

    void miao(){

        cout<<"小猫学小狗:"<<endl;

        dog->wang();

    }

};

Cat* Adapter::cat=new RealCat();

Dog* Adapter::dog=new RealDog();

int main(){

    Adapter adapter;

    adapter.run();

    adapter.miao();

    return 0;

}

3.注意编程规范。

posted @ 2023-10-23 22:50  旺旺大菠萝  阅读(7)  评论(0)    收藏  举报