桥接模式(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的扩展模式。
相关推荐
归去_来兮4 分钟前
深度学习模型在C++平台的部署
c++·深度学习·模型部署
pay4fun1 小时前
2048-控制台版本
c++·学习
hjjdebug3 小时前
ffplay6 播放器关键技术点分析 1/2
c++·ffmpeg·音视频
Azxcc04 小时前
C++异步编程入门
开发语言·c++
吐泡泡_4 小时前
C++(STL源码刨析/vector)
c++
你的冰西瓜4 小时前
C++排序算法全解析(加强版)
c++·算法·排序算法
特立独行的猫a4 小时前
11款常用C++在线编译与运行平台推荐与对比
java·开发语言·c++
笑鸿的学习笔记4 小时前
qt-C++笔记之setCentralWidget的使用
c++·笔记·qt
苏克贝塔6 小时前
Qt 图形视图框架3-事件处理与传播
c++·qt
轩情吖6 小时前
Qt的信号与槽(二)
数据库·c++·qt·信号·connect·信号槽·