C++设计模式-桥接模式

运行在VS2022,x86,Debug下。

29. 桥接模式

  • 桥接模式将抽象与实现分离,使二者可以独立地变化。

  • 应用:如在游戏开发中,多个角色和多个武器交叉组合时。可以使用桥接模式,定义角色抽象类,武器抽象类,两者通过桥接建立关联,使角色和武器之间的关系是松耦合的,可以独立变化,方便游戏后期修改或新填内容。

  • 实现

    • 实现体接口。
    • 具体实现体。
    • 抽象体接口,使用实现体对象。
    • 具体抽象体。
  • 代码如下。

cpp 复制代码
//实现体接口:武器接口
class WeaponImplementor {
public:
    virtual void attack() = 0;
};

//具体实现体:剑
class SwordImplementor : public WeaponImplementor
{
public:
    void attack() { cout << "Slash with Sword" << endl; }
};

//具体实现体:弓箭
class BowImplementor : public WeaponImplementor
{
public:
    void attack() { cout << "Shoot with Bow" << endl; }
};

//具体实现体:枪
class GunImplementor : public WeaponImplementor
{
public:
    void attack() { cout << "Shoot with Gun" << endl; }
};


//抽象体接口:角色接口
class CharacterAbstraction
{
protected:
    WeaponImplementor* usedWeapon;  //桥接关系,使用武器对象

public:
    CharacterAbstraction(WeaponImplementor* weapon): usedWeapon(weapon){}
    void setWeapon(WeaponImplementor* weapon) { usedWeapon = weapon; }
    virtual void operation() = 0;
};

//具体抽象体:战士
class WarriorAbstraction : public CharacterAbstraction
{
public:
    WarriorAbstraction(WeaponImplementor* weapon) : CharacterAbstraction(weapon) {}
    void operation()
    {
        cout << "Warrior ";
        usedWeapon->attack();
    }
};

//具体抽象体:弓手
class ArcherAbstraction : public CharacterAbstraction
{
public:
    ArcherAbstraction(WeaponImplementor* weapon) : CharacterAbstraction(weapon) {}
    void operation()
    {
        cout << "Archer ";
        usedWeapon->attack();
    }
};

int main()
{
    //创建武器
    SwordImplementor sword;
    BowImplementor bow;
    GunImplementor gun;

    //创建角色,并分配武器
    WarriorAbstraction warrior(&gun);
    warrior.operation();
    warrior.setWeapon(&sword);
    warrior.operation();

    ArcherAbstraction archer(&bow);
    archer.operation();

    return 0;
}
相关推荐
生成论实验室9 分钟前
用事件关系网络重新理解AI(二):损失函数、优化器与深度学习的动力学
数据结构·人工智能·深度学习·算法·语言模型
霍霍的袁16 分钟前
【C++初阶】缺省参数(默认参数)详细讲解
开发语言·c++·算法
楼田莉子17 分钟前
C++17新特性:optional/variant/any/string_view
c++·后端·学习
老码观察18 分钟前
设计模式实战解读(一):单例模式——全局唯一实例的正确打开方式
单例模式·设计模式
计算机安禾22 分钟前
【算法分析与设计】第2篇:计算模型与渐进复杂性分析
算法
I Promise3424 分钟前
多传感器融合&模型后处理C++工程师面试参考回答
开发语言·c++·面试
生成论实验室27 分钟前
事件、信息荷与六维态势空间——每一个事件都是一次空间的弯曲
人工智能·算法·语言模型·可信计算技术·安全架构
budingxiaomoli32 分钟前
递归,搜索与回溯算法--递归
算法
风味蘑菇干33 分钟前
Stream基础题目
java·算法
老码观察34 分钟前
设计模式实战解读(二):工厂模式——对象创建的解耦艺术
设计模式·log4j