c++设计模式(适配器模式)

GOOD:双方都不适合修改的时候,可以考虑使用适配器模式
这里写图片描述

例:
#include <iostream>
using namespace std;

class Target
{
public:
    virtual void Request()
    {
        cout<<"普通的请求"<<endl;
    }
};

class Adaptee
{
public:
    void SpecificalRequest()
    {
        cout<<"特殊请求"<<endl;
    }
};

class Adapter :public  Target
{
private:
    Adaptee* ada;
public:
    virtual void Request()
    {
        ada->SpecificalRequest();
        Target::Request();
    }
    Adapter()
    {
        ada=new Adaptee();
    }
    ~Adapter()
    {
        delete ada;
    }
};

客户端:
int main()
{
    Adapter * ada=new Adapter();
    ada->Request();
    delete ada;
    return 0;
}

例二
#include <iostream>
#include <string>
using namespace std;

class Player
{
protected:
    string name;
public:
    Player(string strName) { name = strName; }
    virtual void Attack()=0;
    virtual void Defense()=0;
};

class Forwards : public Player
{
public:
    Forwards(string strName):Player(strName){}
public:
    virtual void Attack()
    {
        cout<<name<<"前锋进攻"<<endl;
    }
    virtual void Defense()
    {
        cout<<name<<"前锋防守"<<endl;
    }
};

class Center : public Player
{
public:
    Center(string strName):Player(strName){}
public:
    virtual void Attack()
    {
        cout<<name<<"中场进攻"<<endl;
    }
    virtual void Defense()
    {
        cout<<name<<"中场防守"<<endl;
    }
};

//为中场翻译
class TransLater: public Player
{
private:
    Center *player;
public:
    TransLater(string strName):Player(strName)
    {
        player = new Center(strName);
    }
    virtual void Attack()
    {
        player->Attack();
    }
    virtual void Defense()
    {
        player->Defense();
    }
};


客户端
int main()
{
    Player *p=new TransLater("小李");
    p->Attack();
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值