桥接模式(Bridge Pattern)是用于把抽象化与实现化解耦,使得二者可以独立变化。这种类型的设计模式属于结构型模式,它通过提供抽象化和实现化之间的桥接结构,来实现二者的解耦。
这种模式涉及到一个作为桥接的接口,使得实体类的功能独立于接口实现类。这两种类型的类可被结构化改变而互不影响。
意图
将抽象部分与实现部分分离,使它们都可以独立的变化。
主要解决
在有多种可能会变化的情况下,用继承会造成类爆炸问题,扩展起来不灵活。
何时使用
实现系统可能有多个角度分类,每一种角度都可能变化。
如何解决
把这种多角度分类分离出来,让它们独立变化,减少它们之间耦合。
应用实例
- 猪八戒从天蓬元帅转世投胎到猪,转世投胎的机制将尘世划分为两个等级,即:灵魂和肉体,前者相当于抽象化,后者相当于实现化。生灵通过功能的委派,调用肉体对象的功能,使得生灵可以动态地选择。
- 使用不同粗细的笔和不同颜色的颜料可以画出粗细、颜色两个维度不同的图画,绘画需要抽象的笔和颜料,具体使用多粗的笔、什么颜料由实现决定,动态选择
优点
- 抽象和实现的分离。
- 优秀的扩展能力。
- 实现细节对客户透明。
缺点
桥接模式的引入会增加系统的理解与设计难度,由于聚合关联关系建立在抽象层,要求开发者针对抽象进行设计与编程。
使用场景
- 如果一个系统需要在构件的抽象化角色和具体化角色之间增加更多的灵活性,避免在两个层次之间建立静态的继承联系,通过桥接模式可以使它们在抽象层建立一个关联关系。
- 对于那些不希望使用继承或因为多层次继承导致系统类的个数急剧增加的系统,桥接模式尤为适用。
- 一个类存在两个独立变化的维度,且这两个维度都需要进行扩展。
注意事项
对于多个独立变化的维度,使用桥接模式再适合不过了。
示例
一套服装由衬衣、裤子、鞋子组成,衬衣分黑白,裤子分长短、鞋子分大小,一共有 2x2x2=8 种组合,如果使用普通继承可能导致类似下面的类爆炸,形成大量重复代码
现在使用桥接模式将三个维度独立,然后将三个维度通过组合创建一套服装
#include "pch.h"#include <iostream>class IShirt{public:virtual int GetPrice() = 0;virtual std::string Info() = 0;};class BlackShirt : public IShirt{public:virtual int GetPrice(){return 20;}virtual std::string Info(){return std::string("Black Shirt");}};class WhiteShirt : public IShirt{public:virtual int GetPrice(){return 25;}virtual std::string Info(){return std::string("White Shirt");}};class IPants{public:virtual int GetPrice() = 0;virtual std::string Info() = 0;};class LongPants : public IPants{public:virtual int GetPrice(){return 45;}virtual std::string Info(){return std::string("Long Pants");}};class ShortPants : public IPants{public:virtual int GetPrice(){return 40;}virtual std::string Info(){return std::string("Short Pants");}};class IShoes{public:virtual int GetPrice() = 0;virtual std::string Info() = 0;};class BigShoes : public IShoes{public:virtual int GetPrice(){return 35;}virtual std::string Info(){return std::string("Big Shoes");}};class SmallShoes : public IShoes{public:virtual int GetPrice(){return 30;}virtual std::string Info(){return std::string("Small Shoes");}};class Suit{public:Suit(IShirt* const pShirt, IPants* const pPants, IShoes* const pShoes){this->pShirt = pShirt;this->pPants = pPants;this->pShoes = pShoes;}~Suit(){delete pShirt;pShirt = nullptr;delete pPants;pPants = nullptr;delete pShoes;pShoes = nullptr;}void Info(){std::cout << "Suit: " << pShirt->Info().c_str()<< " + " << pPants ->Info().c_str()<< " + " << pShoes ->Info().c_str() << std::endl;std::cout << "Price: " << pShirt->GetPrice() + pPants->GetPrice() + pShoes->GetPrice() << std::endl;}private:IShirt* pShirt;IPants* pPants;IShoes* pShoes;};// 调用示例int main(){Suit* SuitA = new Suit(new BlackShirt(), new LongPants(), new BigShoes());SuitA->Info();Suit* SuitB = new Suit(new WhiteShirt(), new ShortPants(), new BigShoes());SuitB->Info();Suit* SuitC = new Suit(new BlackShirt(), new LongPants(), new SmallShoes());SuitC->Info();}
>>>
Suit: Black Shirt + Long Pants + Big Shoes
Price: 100
Suit: White Shirt + Short Pants + Big Shoes
Price: 100
Suit: Black Shirt + Long Pants + Small Shoes
Price: 95
