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 分钟前
用c++求第n个质数
开发语言·c++·算法
snakecy17 分钟前
自然语言处理(NLP)算法原理与实现--Part 1
人工智能·算法·自然语言处理
GISer_Jing18 分钟前
OSG多视口与多通道渲染核心技术解析
c++·3d·新浪微博
萌新彭彭26 分钟前
vLLM主要模块Scheduler详解
算法·源码阅读
灵动小溪29 分钟前
时频信号分析总结
算法
Arva .30 分钟前
责任链设计模式->规则树
设计模式
CoovallyAIHub30 分钟前
让Qwen-VL的检测能力像YOLO一样强,VLM-FO1如何打通大模型的视觉任督二脉
深度学习·算法·计算机视觉
WKP941832 分钟前
命令设计模式
设计模式
玖剹33 分钟前
多线程编程:从日志到单例模式全解析
java·linux·c语言·c++·ubuntu·单例模式·策略模式
2401_8414956442 分钟前
【自然语言处理】基于统计基的句子边界检测算法
人工智能·python·算法·机器学习·自然语言处理·统计学习·句子边界检测算法