设计模式适配器模式

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

c++代码

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

};

class TwoElectricOutlet{
public:
    virtual void connectElectricCurrent() = 0;
};

class ThreeElectricAdapter : public ThreeElectricOutlet{
private:
    TwoElectricOutlet *myOutlet;

public:
    ThreeElectricAdapter(TwoElectricOutlet *outlet);
    void connectElectricCurrent() ;
};

class TwoElectricAdapter : public TwoElectricOutlet{
private:
    ThreeElectricOutlet *myOutlet;

public:
    TwoElectricAdapter(ThreeElectricOutlet *outlet);
    void connectElectricCurrent() ;
};

class Wash : public ThreeElectricOutlet{
public:
    Wash();
    Wash(string s);
    void connectElectricCurrent() ;

private:
    string name;


};
class Tv : public TwoElectricOutlet{
public:
    Tv();
    Tv(string s);
    void connectElectricCurrent() ;
private:
    string name;
};

ThreeElectricAdapter::ThreeElectricAdapter(TwoElectricOutlet *outlet)
{
    myOutlet = outlet;
}

void ThreeElectricAdapter::connectElectricCurrent()
{
    myOutlet->connectElectricCurrent();
    cout << "学猫抓老鼠" << endl;
}

TwoElectricAdapter::TwoElectricAdapter(ThreeElectricOutlet *outlet)
{
    myOutlet = outlet;
}

void TwoElectricAdapter::connectElectricCurrent()
{
    myOutlet->connectElectricCurrent();
    cout <<  "学狗汪汪" << endl;
}


Wash::Wash()
{
    name = "";
}
Wash::Wash(string s)
{
    name = s;
}
void Wash::connectElectricCurrent()
{
    cout << name << endl;
}


Tv::Tv()
{
    name = "";
}

Tv::Tv(string s)
{
    name = s;
}
void Tv::connectElectricCurrent()
{
    cout << name << endl;
}
main()
{
    ThreeElectricOutlet *outlet;
    TwoElectricOutlet *two;

    Wash *wash = new Wash();
    TwoElectricAdapter *te = new TwoElectricAdapter(wash);
    two = te;
    two->connectElectricCurrent();


    Tv *tv = new Tv();
    ThreeElectricAdapter *adapter = new ThreeElectricAdapter(tv);
    outlet = adapter;
    outlet->connectElectricCurrent();
}

 

posted @ 2021-10-03 21:16  大雄的脑袋  阅读(75)  评论(0编辑  收藏  举报