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语言·数据结构·算法·链表
卡戎-caryon1 小时前
【项目实践】贪吃蛇
c语言·数据结构·算法
PeterClerk1 小时前
PCA算法降维代码示例
人工智能·算法·机器学习·pca
Easonmax1 小时前
【C++】 解决 C++ 语言报错:Undefined Reference
java·开发语言·c++
计算机平台作业答案讲解1 小时前
QT实现GIF动图显示(小白版,可直接copy使用)
服务器·开发语言·数据结构·数据库·c++·qt·动态规划
冲鸭嘟嘟可1 小时前
【数据结构】使用C语言 从零实现一个栈的数据结构
c语言·数据结构·算法
峰上踏雪1 小时前
\r:回车符 与 \n:换行符
linux·运维·c++
小白菜又菜2 小时前
Leetcode 516. Longest Palindromic Subsequence
算法·leetcode·职场和发展
Easonmax2 小时前
【C++】 解决 C++ 语言报错:Invalid Cast
java·开发语言·c++