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;
}
相关推荐
量子炒饭大师1 分钟前
【C++入门】零域终端的虚空指针协议——【nullptr】还在为编译器给NULL匹配为int而头疼?nullptr给予你全新的字面量!
开发语言·c++·nullptr
阿豪只会阿巴8 分钟前
【多喝热水系列】从零开始的ROS2之旅——Day10 话题的订阅与发布1:Python
开发语言·c++·python·ubuntu·ros2
da_vinci_x15 分钟前
武器设计实战:一把大剑裂变 5 种属性?Structure Ref 的“换肤”魔法
游戏·3d·设计模式·ai作画·aigc·设计师·游戏美术
junziruruo21 分钟前
t-SNE可视化降维技术(以FMTrack频率感知与多专家融合文章中的内容为例)
人工智能·算法
羊小猪~~23 分钟前
【QT】--文件操作
前端·数据库·c++·后端·qt·qt6.3
藦卡机器人31 分钟前
自动焊接机器人的核心技术要求与标准
人工智能·算法·机器人
2501_940315261 小时前
【无标题】1.17给定一个数将其转换为任意一个进制数(用栈的方法)
开发语言·c++·算法
栈与堆1 小时前
LeetCode 21 - 合并两个有序链表
java·数据结构·python·算法·leetcode·链表·rust
fpcc1 小时前
C++23中的模块应用说明之五综合应用和重点分
c++·c++23
鹿角片ljp1 小时前
力扣7.整数反转-从基础到边界条件
算法·leetcode·职场和发展