66 lines
1.6 KiB
Dart
66 lines
1.6 KiB
Dart
/**
|
||
桥接(Bridge)
|
||
|
||
意图:将抽象部分与实现部分分离,使它们都可以独立的变化。
|
||
主要解决:在有多种可能会变化的情况下,用继承会造成类爆炸问题,扩展起来不灵活。
|
||
何时使用:实现系统可能有多个角度分类,每一种角度都可能变化。
|
||
如何解决:把这种多角度分类分离出来,让它们独立变化,减少它们之间耦合。
|
||
*/
|
||
main(List<String> args) {
|
||
Shape redCircle = new Circle(100, 100, 10, new RedCircle());
|
||
Shape greenCircle = new Circle(100, 100, 10, new GreenCircle());
|
||
|
||
redCircle.draw();
|
||
greenCircle.draw();
|
||
}
|
||
|
||
//////////////////////////////////////////////////////////////////
|
||
|
||
///
|
||
/// 创建桥接实现接口
|
||
///
|
||
abstract class DrawAPI {
|
||
void drawCircle(int radius, int x, int y);
|
||
}
|
||
|
||
///
|
||
/// 创建实现了 DrawAPI 接口的实体桥接实现类
|
||
///
|
||
class RedCircle implements DrawAPI {
|
||
@override
|
||
void drawCircle(int radius, int x, int y) {
|
||
print("Drawing Circle[ color: red, radius: $radius"
|
||
", x: $x, y:$y]");
|
||
}
|
||
}
|
||
|
||
class GreenCircle implements DrawAPI {
|
||
@override
|
||
void drawCircle(int radius, int x, int y) {
|
||
print("Drawing Circle[ color: green, radius: $radius"
|
||
", x: $x, y:$y]");
|
||
}
|
||
}
|
||
|
||
///
|
||
/// 使用 DrawAPI 接口创建抽象类 Shape
|
||
///
|
||
abstract class Shape {
|
||
DrawAPI _drawAPI;
|
||
Shape(this._drawAPI);
|
||
void draw();
|
||
}
|
||
|
||
///
|
||
/// 创建实现了 Shape 接口的实体类
|
||
///
|
||
class Circle extends Shape {
|
||
int _x, _y, _radius;
|
||
|
||
Circle(this._x, this._y, this._radius, DrawAPI drawAPI) : super(drawAPI);
|
||
|
||
void draw() {
|
||
_drawAPI.drawCircle(_radius, _x, _y);
|
||
}
|
||
}
|