量化交易之设计模式篇 - 适配器模式

本文通过两个示例介绍了适配器模式在实际编程中的应用。第一个例子展示了如何使用适配器将不兼容的Adaptee类转换为Target接口。第二个例子中,Translater类作为适配器,使得Player接口能够调用Center类的方法,实现了不同角色之间的兼容。适配器模式在不修改原有类的情况下,提供了一种使不同组件协同工作的解决方案。
摘要由CSDN通过智能技术生成
/*
 * 适配器模式
 * 适用于双方都不适合修改的时候
 */

class Target {
public:
    virtual void request() {
        std::cout << "Target request." << std::endl;
    }
};
class Adaptee {
public:
    virtual void specialRequest() {
        std::cout << "Adaptee specialRequest." << std::endl;
    }
};

class Adapter: public Target {
public:
    Adapter() {
        this->adaptee = new Adaptee();
    }
    virtual ~Adapter() {
        delete this->adaptee;
    }
    virtual void request() {
        Target::request();
        this->adaptee->specialRequest();
    }

private:
    Adaptee* adaptee;
};

int main() {

    Adapter* adapter = new Adapter();
    adapter->request();

    delete adapter;

    return 0;
}
#include <thread>
#include <iostream>
#include <vector>
using namespace std;

class Player {
public:
    Player(string name): name(name) {}
    virtual ~Player() = default;
    virtual void attack() = 0;
    virtual void deffence() = 0;

protected:
    string name;
};
class Forwards: public Player {
public:
    Forwards(string name): Player(name) {}
    virtual void attack() {
        std::cout << this->name << " Forwards attack." << std::endl;
    }
    virtual void deffence() {
        std::cout << this->name << " Forwards deffence." << std::endl;
    }
};
class Center: public Player {
public:
    Center(string name): Player(name) {}
    virtual void attack() {
        std::cout << this->name << " Center attack." << std::endl;
    }
    virtual void deffence() {
        std::cout << this->name << " Center deffence." << std::endl;
    }
};

class Translater: public Player {
public:
    Translater(string name): Player(name) {
        this->player = new Center(name);
    }
    virtual ~Translater() {
        delete this->player;
    }

    virtual void attack() {
        this->player->attack();
    }
    virtual void deffence() {
        this->player->deffence();
    }

private:
    Player* player;
};

int main() {

    Player* player = new Translater("Ronaldo");
    player->attack();
    player->deffence();

    delete player;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值