C++设计模式-桥接(Bridge)

目录

C++设计模式-桥接(Bridge)

一、意图

二、适用性

三、结构

四、参与者

五、代码


C++设计模式-桥接(Bridge)

一、意图

将抽象部分与它的实现部分分离,使它们都可以独立地变化。

二、适用性

  • 你不希望在抽象和它的实现部分之间有一个固定的绑定关系。例如这种情况可能是因为,在程序运行时刻实现部分应可以被选择或者切换。
  • 类的抽象以及它的实现都应该可以通过生成子类的方法加以扩充。这时Bridge模式使你可以对不同的抽象接口和实现部分进行组合,并分别对它们进行扩充。
  • 对一个抽象的实现部分的修改应对客户不产生影响,即客户的代码不必重新编译。
  • (C++)你想对客户完全隐藏抽象的实现部分。在C++中,类的表示在类接口中是可见的。
  • 有许多类要生成。这样一种类层次结构说明你必须将一个对象分解成两个部分。Rumbaugh称这种类层次结构为"嵌套的普化"(nested generalizations )。
  • 你想在多个对象间共享实现(可能使用引用计数),但同时要求客户并不知道这一点。一个简单的例子便是Coplien的String类Cop92,在这个类中多个对象可以共享同一个字符串表示(S tringRep)。

三、结构

四、参与者

  • Abstraction

定义抽象类的接口。

维护一个指向Implementor类型对象的指针。

  • RefinedAbstraction

扩充由Abstraction定义的接口。

  • Implementor

定义实现类的接口,该接口不一定要与Abstraction的接口完全一致;事实上这两个接口可以完全不同。一般来讲,Implementor接口仅提供基本操作,而Abstraction则定义了基本这些基本操作的较高层次的操作。

  • ConcreteImplementor

实现了Implementor接口并定义它的具体实现。

五、代码

cpp 复制代码
#include<iostream>
using namespace std;

class Implementor {
public:
	virtual void OperationImp() = 0;
};

class ConcreteImplementorA : public Implementor {
public:
	virtual void OperationImp() {
		cout << "Concrete Implementor A" << endl;
	}
};

class ConcreteImplementorB : public Implementor {
public:
	virtual void OperationImp() {
		cout << "Concrete Implementor B" << endl;
	}
};

class Abstraction {
public:
	virtual void Operation() = 0;
};

class RefinedAbstraction : public Abstraction {
public:
	RefinedAbstraction(Implementor* TempImplementor) {
		this->implementor = TempImplementor;
	}
	void Operation() {
		implementor->OperationImp();
	}
private:
	Implementor* implementor;
};

int main() {
	
	Implementor* implementorA = new ConcreteImplementorA;
	Abstraction* abstractionA = new RefinedAbstraction(implementorA);
	abstractionA->Operation();

	Implementor* implementorB = new ConcreteImplementorB;
	Abstraction* abstractionB = new RefinedAbstraction(implementorB);
	abstractionB->Operation();

	return 0;
}
相关推荐
众少成多积小致巨1 天前
JNI (Java Native Interface) 技术手册中文参考指南
android·java·c++
槑有老呆1 天前
别再手搓 Prompt 了,那个叫"手动挡循环"
设计模式
用户6919026813392 天前
Vibe Coding 开发项目的基本范式
人工智能·设计模式·代码规范
怕浪猫3 天前
领域特定语言(Domain-Specific Language, DSL)
设计模式·程序员·架构
Larcher5 天前
AI Loop:让AI像人一样自主完成任务的核心机制
javascript·人工智能·设计模式
clint4565 天前
C++进阶(1)——前景提要
c++
夜悊5 天前
C++代码示例:进制数简单生成工具
c++
郝学胜_神的一滴5 天前
CMake 021: IF 条件判据详诠
c++·cmake
_wyt0016 天前
洛谷 B3930 [GESP202312 五级] 烹饪问题 题解
c++·gesp