美文网首页
适配器模式

适配器模式

作者: 张霸天 | 来源:发表于2017-03-27 17:56 被阅读0次

适配器模式: 将一个类的接口转化为客户希望的另一个接口;adapter 模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。



#include <iostream>

using namespace std;

class Player {
protected:
    string name;
    
public:
    Player(string name) :name(name){};
    virtual ~Player(){};

    virtual void Attack(){};
    virtual void Defense(){};
};

class Forward:public Player {
    
public:
    Forward(string name) : Player(name){}
    ~Forward(){};
    void Attack(){
        cout<< "forword attck:"<<name<<endl;
    }
    
    void Defense(){
        cout<< "forword defence:"<<name<<endl;
    }
};

class Center:public Player {
    
public:
    Center(string name) : Player(name){}
    ~Center(){};
    void Attack(){
        cout<< "center attck:"<<name<<endl;
    }
    
    void Defense(){
        cout<< "center defence:"<<name<<endl;
    }
    
};

class ForeignCenter {
private:
    string name;
public:
    
    void setname(string name) {this->name = name;}
    string getname(){return this->name;}
    
    void Attack(){
        cout<< " 进攻:"<<name<<endl;
    }
    
    void Defense(){
        cout<< "防守:"<<name<<endl;
    }
};

class Translator : public Player {
private:
    ForeignCenter * wjzf ;
    
public:
    Translator(string name):Player(name){
        wjzf = new ForeignCenter();
        wjzf->setname(name);
    }
    ~Translator(){
        delete wjzf;
    }
    
    void Attack(){
        wjzf->Attack();
    }
    
    void Defense(){
        wjzf->Defense();
    }
};


void testLesson13(){
    Player * b = new Forward("batier");
    b->Attack();
    
    Player *m = new Translator("yaoming");
    m ->Attack();
}


适配器的使用场景。想使用一个已经存在的类,但如果它的接口,也就是它的方法和你的要求不相同时,就应该考虑适配器模式。
在双方都不太容易修改的时候再使用适配器模式,争取早点重构。不要问题扩大

相关文章

  • Java设计模式(二)

    talk is cheap show me the code 适配器模式 类适配器模式 接口适配器模式 对象适配器...

  • 适配器模式

    目录 1、什么是适配器模式? 2、适配器模式结构? 3、如何实现适配器模式? 4、适配器模式的特点? 5、适配器模...

  • 设计模式之适配器模式

    适配器模式: 类适配器模式、对象适配器模式、接口适配器模式 1.类适配器模式:新的接口出现了,但是和老的接口不兼容...

  • 学习iOS设计模式第一章 适配器(Adapter)

    今天学习了iOS设计模式中的适配器模式,适配器有两种模式对象适配器模式-- 在这种适配器模式中,适配器容纳一个它包...

  • 第4章 结构型模式-适配器模式

    一、适配器模式简介 二、适配器模式的优点 三、适配器模式的实例

  • 设计模式(Design Patterns)适配器模式(Adapt

    适配器模式主要分为三类:类的适配器模式、对象的适配器模式、接口的适配器模式。 类的适配器模式 场景:将一个类转换成...

  • 适配器模式

    适配器模式主要分为三类:类的适配器模式、对象的适配器模式、接口的适配器模式。适配器模式将某个类的接口转换成客户端期...

  • 适配器模式

    先直观感受下什么叫适配器 适配器模式有类的适配器模式和对象的适配器模式两种不同的形式。 类适配器模式 对象适配器模...

  • 适配器模式

    适配器模式 一、适配器模式定义 适配器模式的定义是,Convert the interface of a clas...

  • 设计模式:结构型

    享元模式 (Pools,Message) 代理模式 适配器模式 :类适配器和对象适配器 装饰者模式 外观模式 桥接...

网友评论

      本文标题:适配器模式

      本文链接:https://www.haomeiwen.com/subject/mxofottx.html