桥接模式(C++)

定义

将抽象部分(业务功能)与实现部分(平台实现)分离,使它们都可以独立地变化。

使用场景

  • 由于某些类型的固有的实现逻辑,使得它们具有两个变化的维度,乃至多个纬度的变化。
  • 如何应对这种"多维度的变化"?如何利用面向对象技术来使得类型可以轻松地沿着两个乃至多个方向变化,而不引入额外的复杂度?

结构

代码示例

cpp 复制代码
//Bridge.h
/****************************************************/
#ifndef BRIDGE_H
#define BRIDGE_H
#include<iostream>
using namespace std;
 
//创建桥接实现接口drawapi。
class drawapi
{
public:
	drawapi() {};
	virtual ~drawapi() {};
	virtual void drawcircle(int radius,int x,int y)=0;
	
};
 
//创建实现了DrawAPI接口的实体桥接实现类redcircle。
class redcircle:drawapi
{
public:
	redcircle() {};
	virtual ~redcircle() {};
	
	void drawcircle(int radius, int x, int y) { cout << "color: red " << "sadius: " << radius << " x: " << x << " y: " << y << endl; };
};
 
//创建实现了DrawAPI接口的实体桥接实现类greencircle。
class greencircle :drawapi
{
public:
	greencircle() {};
	virtual ~greencircle() {};
 
	void drawcircle(int radius, int x, int y) { cout << "color: green " << "sadius: " << radius << " x: " << x << " y: " << y << endl; };
};
 
//使用DrawAPI接口创建抽象类Shape。
class shape
{
public:
	shape() {};
	virtual ~shape() { delete mdrawapi; mdrawapi = NULL; };
	virtual void draw()=0;
 
protected:
	drawapi *mdrawapi;
};
 
//创建实现了Shape接口的实体类circle。
class circle :shape
{
public:
	circle(int tx, int ty, int tradius, drawapi *tdrawapi) { mdrawapi = tdrawapi; x = tx; y = ty; radius = tradius; };
	~circle() {};
 
	void draw() { mdrawapi->drawcircle(radius,x,y); };
private:
	int x;
	int y;
	int radius;
};
 
#endif
cpp 复制代码
//test.cpp
/****************************************************/
#include <iostream>
#include <string>
#include "Bridge.h"
int main()
{

	shape *t1 = (shape*)new circle(100, 100, 10, (drawapi*)new redcircle());
	shape *t2 = (shape*)new circle(35, 74, 10, (drawapi*)new greencircle());
 
	t1->draw();
	t2->draw();
 
	delete t1;
	t1 = NULL;
 
	delete t2;
	t2 = NULL;
	return 0;
}

运行结果

要点总结

  • Bridge模式使用"对象间的组合关系"解耦了抽象和实现之间固有的绑定关系,使得抽象和实现可以沿着各自的维度来变化。所谓抽象和实现沿着各自纬度的变化,即"子类化"它们。
  • Bridge模式有时候类似于多继承方案,但是多继承方案往往违背单一职责原则(即一个类只有一个变化的原因), 复用性比较差。Bridge模式是比多继承方案更好的解决方法。
  • Bridge模式的应用一般在"两个非常强的变化维度",有时一一个类也有多于两个的变化维度,这时可以使用Bridge的扩展模式。
相关推荐
码匠许师傅11 小时前
【设计模式精讲】14.外观模式(Facade)
c++·设计模式·uml·外观模式
xxwxx__13 小时前
C++ list 深度解析:从使用原理到模拟实现
开发语言·c++·list
Chester_199913 小时前
CSP202303C.LDAP
开发语言·c++·蓝桥杯·stl
j7~14 小时前
【C++】《unordered系列关联式容器以及哈希底层、哈希冲突、闭散列与开散列完整解析》
c++·哈希算法·开散列·闭散列·unordered_map·unordered_set·哈希底层结构
2402_8828938615 小时前
封装红黑树实现map和set —— 从源码到模拟实现
c++·set·map
神仙别闹16 小时前
基于C++ MFC 实现的智慧公交系统
开发语言·c++·mfc
dear_bi_MyOnly17 小时前
函数模块化:企业级项目高效之道
c++·后端·学习
码匠许师傅17 小时前
【设计模式精讲】13.装饰器模式(Decorator)
c++·设计模式·uml·装饰器模式
OPEN-F17 小时前
C++综合实战:面向对象图书管理系统
开发语言·c++
NeoGressAI外贸数字化18 小时前
外贸独立站零询盘排查:从 Google Search Console 到 PageSpeed 的技术实操
开发语言·c++