将继承改为组合,可将一个大类或一系列紧密相关的类拆分为抽象和实现两个独立的层次结构, 从而能在开发时分别使用。
实例
抽象部分:Pen:BigPen,SmallPen
Abstraction.h
#ifndef ABSTRACTION_H_
#define ABSTRACTION_H_
#include <string>
#include "Implementation.h"
// 抽象类: Pen
class Pen {
public:
virtual void draw(std::string name) = 0;
void set_color(Color* color) {
color_ = color;
}
protected:
Color* color_;
};
#endif // ABSTRACTION_H_
将Color作为Pen的一个属性。
RefinedAbstraction.h
#ifndef REFINED_ABSTRACTION_H_
#define REFINED_ABSTRACTION_H_
#include <string>
#include "Abstraction.h"
// 精确抽象类: BigPen
class BigPen : public Pen {
public:
void draw(std::string name) {
std::string pen_type = "大号钢笔绘制";
color_->bepaint(pen_type, name);
}
};
// 精确抽象类: SmallPencil
class SmallPencil : public Pen {
public:
void draw(std::string name) {
std::string pen_type = "小号铅笔绘制";
color_->bepaint(pen_type, name);
}
};
#endif // REFINED_ABSTRACTION_H_
实现部分:Color:Red、Green
Implementation.h
#ifndef IMPLEMENTATION_H_
#define IMPLEMENTATION_H_
#include <string>
#include <iostream>
// 实现类接口: 颜色
class Color {
public:
virtual void bepaint(std::string pen_type, std::string name) = 0;
};
#endif // IMPLEMENTATION_H_
ConcreteImplementation.h
#ifndef CONCRETE_IMPLEMENTATION_H_
#define CONCRETE_IMPLEMENTATION_H_
#include <string>
#include "Implementation.h"
// 具体实现类: Red
class Red : public Color {
public:
void bepaint(std::string pen_type, std::string name) override {
std::cout << pen_type << "红色的" << name << "." << std::endl;
}
};
// 具体实现类: Green
class Green : public Color {
public:
void bepaint(std::string pen_type, std::string name) override {
std::cout << pen_type << "绿色的" << name << "." << std::endl;
}
};
#endif // CONCRETE_IMPLEMENTATION_H_
main.cpp
#include "ConcreteImplementation.h"
#include "RefinedAbstraction.h"
int main() {
// 客户端根据运行时参数获取对应的Color和Pen
Color* color = new Red();
Pen* pen = new SmallPencil();
pen->set_color(color);
pen->draw("太阳");
delete color;
delete pen;
}
编译运行:
$g++ -g main.cpp -o bridge -std=c++11
$./bridge
小号铅笔绘制红色的太阳.