章XVII - アダプタモード

アダプタモード(アダプタ):クラス・インタフェースのクライアントが別のインターフェイスを期待して変換します。アダプタパターンは、そうでないため、互換性のないインタフェースのこれらのクラスが一緒に仕事に一緒に働くことができないことができます。

ソフトウェア開発では、データとシステムの動作が正しいですが、インターフェイスと一致しない場合、我々はアダプターの使用を検討すべき、目的が一致するインターフェイスのコントロール外に元のオブジェクトを作ることです。アダプタモードは、主に使用されている既存のクラスの一部を再利用したいのですが、マルチプレックス環境とのインターフェイスと矛盾しています。

絵

基本的なコード

#include<iostream>
#include<string>
#include<vector>

using namespace std;

//Target(客户所期待的接口。目标可以是具体的或抽象的类,也可以是接口)
class Target
{
public:
    virtual void Request()
    {
        cout << "普通请求!" << endl;
    }
};

//Adaptee(需要适配的类)
class Adaptee
{
public:
    void SpecificRequest()
    {
        cout << "特殊请求!" << endl;
    }
};

//Adapter(通过在内部包装一个Adapter对象,把源原接口转换成目标接口)
class Adapter :public Target
{
private:
    Adaptee* adaptee;
public:
    Adapter() :adaptee(new Adaptee()) {}
    void Request()
    {
        adaptee->SpecificRequest();
    }
};

int main()
{
    Target* target = new Adapter();
    target->Request();


    system("pause");
    return 0;
}

バスケットボール翻訳アダプタ

絵

#include<iostream>
#include<string>
#include<vector>

using namespace std;

class Player
{
protected:
    string name;
public:
    Player(string name_t)
    {
        name = name_t;
    }

    virtual void Attack() = 0;
    virtual void Defense() = 0;
};

class Forwards :public Player
{
public:
    Forwards(string name) : Player(name)
    {

    }

    void Attack()
    {
        cout << "前锋" << name << "进攻" << endl;
    }

    void Defense()
    {
        cout << "前锋" << name << "防守" << endl;
    }
};

class Guards :public Player
{
public:
    Guards(string name) : Player(name)
    {

    }

    void Attack()
    {
        cout << "后卫" << name << "进攻" << endl;
    }

    void Defense()
    {
        cout << "后卫" << name << "防守" << endl;
    }
};

//外籍中锋
class ForeignCenter
{
private:
    string name;
public:
    string getName() { return name; }
    void setName(string name_t) { name = name_t; }

    void Jingong()
    {
        cout << "外籍中锋" << name << "进攻" << endl;
    }

    void Fangshou()
    {
        cout << "外籍中锋" << name << "防守" << endl;
    }
};

class Translator : public Player
{
private:
    ForeignCenter* wjzf;
public:
    Translator(string name_t)
        : Player(name_t)
    {
        wjzf = new ForeignCenter();
        wjzf->setName(name);
    }

    void Attack()
    {
        wjzf->Jingong();
    }

    void Defense()
    {
        wjzf->Fangshou();
    }
};



int main()
{
    Player* b = new Forwards("巴蒂尔");
    b->Attack();

    Player* m = new Guards("麦迪");
    m->Attack();

    Player* ym = new Translator("姚明");
    ym->Attack();
    ym->Defense();

    system("pause");
    return 0;
}

おすすめ

転載: www.cnblogs.com/wfcg165/p/12031834.html