桥接模式
定义
桥接模式(Bridge Pattern):将抽象部分与它的实现部分分离,使它们都可以独立地变化。
优点
- 实现抽象和实现的分离
- 桥接模式提高了系统的可扩充性,在两个变化维度中任意扩展一个维度,都不需要修改原有系统
- 桥接模式有时类似于多继承方案,但是多继承方案违背了类的单一职责原则(即一个类只有一个变化的原因),复用性比较差,而且多继承结构中类的个数非常庞大,桥接模式是比多继承方案更好的解决方法
缺点
- 桥接模式的引入会增加系统的理解与设计难度,由于聚合关联关系建立在抽象层,要求开发者针对抽象进行设计与编程。
- 桥接模式要求正确识别出系统中两个独立变化的维度,因此其使用范围具有一定的局限性。
场景
- 一个类存在两个独立变化的维度,且这两个维度都需要进行扩展。
- 如果一个系统需要在构件的抽象化角色和具体化角色之间增加更多的灵活性,避免在两个层次之间建立静态的继承联系,通过桥接模式可以使它们在抽象层建立一个关联关系。
- 对于那些不希望使用继承或因为多层次继承导致系统类的个数急剧增加的系统,桥接模式尤为适用。
代码
package Bridge import "fmt" type Draw interface { DrawCircle(radius, x, y int) } type RedCircle struct { } func (r *RedCircle) DrawCircle(radius, x, y int) { fmt.Println("radius,x,y", radius, x, y) } type YellowCircle struct { } func (r *YellowCircle) DrawCircle(radius, x, y int) { fmt.Println("radius,x,y", radius, x, y) } type Shape struct { draw Draw } func (s *Shape) Shape(d Draw) { s.draw = d } type Circle struct { shape Shape x int y int radius int } func (c *Circle) Constructor(x, y, radius int, draw Draw) { c.x = x c.y = y c.radius = radius c.shape.Shape(draw) } func (c *Circle) Draw() { c.shape.draw.DrawCircle(c.radius, c.x, c.y) }
package Bridge import "testing" func TestCircle_Draw(t *testing.T) { red := Circle{} red.Constructor(100, 100, 10, &RedCircle{}) red.Draw() yellow := Circle{} yellow.Constructor(200, 200, 20, &YellowCircle{}) yellow.Draw() }
其他设计模式
设计模式Git源代码
00简单工厂模式
01工厂方法模式
02抽象工厂模式
03外观模式
04建造者模式
05桥接模式
06命令模式
07迭代器模式
08模板模式
09访问者模式
10备忘录模式
11责任链模式
12中介模式
13原型模式
14状态模式
15策略模式
16享元模式
17组合模式
18解释器模式
19单例模式
20适配器模式
21代理模式
22装饰器模式
23观察者模式