桥接器模式(Bridge Pattern)是一种结构设计模式,它将抽象部分与实现部分分离,使它们可以独立地变化。桥接器模式通常用于需要在多个维度上扩展和变化的情况下,将抽象和实现解耦。
以下是一个简单的C++桥接器模式的示例:
#include <iostream>
// 实现接口
class Implementor
{
public:
virtual void operationImpl() = 0;
};
// 具体实现类A
class ConcreteImplementorA : public Implementor
{
public:
void operationImpl() override
{
std::cout << "Concrete Implementor A operation" << std::endl;
}
};
// 具体实现类B
class ConcreteImplementorB : public Implementor
{
public:
void operationImpl() override
{
std::cout << "Concrete Implementor B operation" << std::endl;
}
};
// 抽象类
class Abstraction
{
protected:
Implementor *implementor;
public:
Abstraction(Implementor *implementor) : implementor(implementor) {}
virtual void operation() = 0;
};
// 扩展抽象类
class RefinedAbstraction : public Abstraction
{
private:
std::string type;
public:
RefinedAbstraction(Implementor *implementor, std::string type) : Abstraction(implementor), type(type) {}
void operation() override
{
std::cout << "type: " << type << " ";
implementor->operationImpl();
}
};
int main()
{
Implementor *implementorA = new ConcreteImplementorA();
Abstraction *abstractionA = new RefinedAbstraction(implementorA, "A");
abstractionA->operation();
abstractionA = new RefinedAbstraction(implementorA, "B");
abstractionA->operation();
delete implementorA;
delete abstractionA;
Implementor *implementorB = new ConcreteImplementorB();
Abstraction *abstractionB = new RefinedAbstraction(implementorB, "C");
abstractionB->operation();
abstractionB = new RefinedAbstraction(implementorB, "D");
abstractionB->operation();
delete implementorB;
delete abstractionB;
return 0;
}
运行结果:
type: A Concrete Implementor A operation
type: B Concrete Implementor A operation
type: C Concrete Implementor B operation
type: D Concrete Implementor B operation
在上述示例中,Implementor是实现接口,定义了实现部分的操作方法。ConcreteImplementorA和ConcreteImplementorB是具体实现类,分别实现了实现接口的操作方法。Abstraction是抽象类,包含了一个实现接口的成员变量,并定义了抽象部分的操作方法。RefinedAbstraction是扩展抽象类,继承了抽象类,并实现了抽象部分的操作方法。
在main()函数中,首先创建了一个具体实现类ConcreteImplementorA的对象,并将其传递给扩展抽象类RefinedAbstraction的构造函数,创建了一个抽象类对象abstractionA。通过调用抽象类的operation()方法,实现了抽象部分的操作。然后,创建了一个具体实现类ConcreteImplementorB的对象,并将其传递给扩展抽象类RefinedAbstraction的构造函数,创建了另一个抽象类对象abstractionB。同样地,通过调用抽象类的operation()方法,实现了抽象部分的操作。
通过桥接器模式,可以将抽象部分与实现部分分离,使它们可以独立地变化。桥接器模式提供了更好的灵活性和可扩展性,可以在运行时动态地将不同的抽象部分和实现部分组合起来,而不影响彼此。