将抽象部分与实现部分分离,使它们都可以独立的变化
需要多角度去分类实现对象, 而只用继承会造成大量的类增加, 不能满足开放-封闭原则时, 就应该要考虑用桥接模式
适用于一个类存在两个独立变化的维度, 且每个维度都需要进行扩展
示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
|
interface IColor { void Paint(); } public class RedColor : IColor { public void Paint() { Console.WriteLine("RedColor"); } } public class BlueColor : IColor { public void Paint() { Console.WriteLine("BlueColor"); } } public abstract class Shape { protected IColor color; public void SetColor(IColor color) { this.color = color; } public abstract void Draw(); } public class Circle : Shape { public override void Draw() { Console.WriteLine("Circle"); color.Paint() } } public class Rectangle : Shape { public override void Draw() { Console.WriteLine("Rectangle"); color.Paint() } }
Shape shape = new Circle(); shape.SetColor(new BlueColor()); shape.Draw();
|