使用C++语言实现桥梁模式源代码解析
桥梁模式是一种结构型设计模式,用于将抽象和实现解耦,并能够在运行时进行独立的扩展。以下是使用C++语言实现桥梁模式的完整源代码及其详细解析。
(1)创建抽象类
首先需要定义一个抽象类,用于声明所有具体实现类中共有的方法,此处定义了Shape抽象类,并声明了draw()纯虚方法。
class Shape {
public:
virtual void draw() = 0;
};
(2)创建实现类
接着需要创建具体实现类,这些类将实现Shape抽象类中声明的纯虚方法。此处创建Rectangle和Circle类分别继承自Shape抽象类。
class Rectangle: public Shape {
public:
void draw() {
cout << "Drawing Rectangle shape" << endl;
}
};
class Circle: public Shape {
public:
void draw() {
cout << "Drawing Circle shape" << endl;
}
};
(3)创建桥梁类
创建桥梁类,该类将作为Shape和DrawAPI之间的桥梁。此处创建ShapeBridge类,包含DrawAPI纯虚方法。
class DrawAPI {
public:
virtual void draw() = 0;
}
订阅专栏 解锁全文
987

被折叠的 条评论
为什么被折叠?



