目录
1.意图
将一个抽象类从它的具体实现中解耦出来,这样这两个类可以独立的变化,互不影响。
2.UML类图
3.GOF角色说明
Abstraction(抽象类)
定义抽象类的接口。维护一个指向Implementor类型对象的指针。
RefinedAbstraction
扩充由Abstraction定义的接口。
Implementor
定义实现类的接口。该接口不一定要与Abstraction的接口完全一致:事实上这两个接口可以完全不同。一般来讲,Implementor接口仅提供基本操作,而Abstraction则定义了基于这些操作的较高层次的操作。
ConcreteImplementor
实现Implementor接口并定义它的具体实现。
4.代码实现
#include<iostream>
using namespace std;
//Implementor
class DrawImplementor {
public:
virtual void drawSquare(double) = 0;
virtual ~DrawImplementor() {
}
};
// ConcreteImplementor A
class DrawWithBrush: public DrawImplementor {
public:
DrawWithBrush() {
}
virtual ~DrawWithBrush() {
}
void drawSquare(double side) {
cout<<"DrawWithBrush->square with side="<<side<<endl;
}
};
// ConcreteImplementor B
class DrawWithPencil: public DrawImplementor {
public:
DrawWithPencil() {
}
virtual ~DrawWithPencil() {
}
void drawSquare(double side) {
cout<<"DrawWithPencil->square with side="<<side<<endl;
}
};
// Abstraction
class Shape {
public:
virtual void draw() = 0;
virtual void resize(double) = 0;
virtual ~Shape() {
}
};
// Refined Abstraction
class Square: public Shape {
public:
Square(double s, DrawImplementor& impl):
side(s),implementor(impl) {
}
virtual ~Square() {
}
void draw() {
implementor.drawSquare(side);
}
void resize(double pct) {
side *= pct;
}
private:
double side;
DrawImplementor& implementor;
};
int main(int argc, char *argv[]) {
DrawWithBrush brush;
DrawWithPencil pencil;
Square sq1(1,brush);
Square sq2(2,pencil);
sq1.resize(10);
sq1.draw();
sq2.resize(10);
sq2.draw();
return 0;
}
运行结果:
DrawWithBrush->square with side=10
DrawWithPencil->square with side=20