您的位置:首页 > 其它

设计模式(5) - Bridge桥接模式

2013-12-22 00:05 417 查看

1. 意图

将一个抽象类从它的具体实现中解耦出来,这样这两个类可以独立的变化,互不影响。

2. UML类图



3. 代码实现

#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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: