设计模式(十八)桥接模式
桥接模式(Bridge),将抽象部分与它的实现部分分离,使它们都可以独立地变化。这里 “抽象与它的实现分离”,并不是说,让抽象类与其派生类分离,因为这没有任何意义。实现指的是抽象类和它的派生类用来实现自己的对象。
桥接模式的核心意图就是把这些实现独立出来,让它们各自地变化。这就使得每种实现的变化不会影响其他实现,从而达到应对变化的目的。

基本代码
1 abstract class Implementor 2 { 3 public abstract void Operation(); 4 } 5 // 6 class ConcreteImplementorA : Implementor 7 { 8 public override void Operation() 9 { 10 Console.WriteLine("具体实现 A 的方法执行"); 11 } 12 } 13 // 14 class ConcreteImplementorB : Implementor 15 { 16 public override void Operation() 17 { 18 Console.WriteLine("具体实现 B 的方法执行"); 19 } 20 } 21 // 22 class Abstraction 23 { 24 protected Implementor implementor; 25 26 public void SetImplementor(Implementor implementor) 27 { 28 this.implementor = implementor; 29 } 30 31 public virtual void Operation() 32 { 33 implementor.Operation(); 34 } 35 } 36 // 37 class RefinedAbstraction : Abstraction 38 { 39 public override void Operation() 40 { 41 implementor.Operation(); 42 } 43 } 44 45 // 客户端 46 static void Main(string[] args) 47 { 48 Abstraction ab = new RefinedAbstraction(); 49 50 ab.SetImplementor(new ConcreteImplementorA()); 51 ab.Operation(); 52 53 ab.SetImplementor(new ConcreteImplementorB()); 54 ab.Operation(); 55 56 Console.Read(); 57 }
【例】手机品牌与软件(手机品牌包含手机软件,但手机软件并不是品牌的一部分,所以它们之间是聚合关系)

基本代码
1 // 手机软件 2 abstract class HandsetSoft 3 { 4 public abstract void Run(); 5 } 6 7 // 手机游戏 8 class HandsetGame : HandsetSoft 9 { 10 public override void Run() 11 { 12 Console.WriteLine("运行手机游戏"); 13 } 14 } 15 16 // 手机通讯录 17 class HandsetAddressList : HandsetSoft 18 { 19 public override void Run() 20 { 21 Console.WriteLine("运行手机通讯录"); 22 } 23 } 24 25 // 手机品牌(品牌需要关注软件,所以设置手机软件) 26 abstract class HandsetBrand 27 { 28 protecteed HandsetSoft soft; 29 30 // 设置手机软件 31 public void SetHandsetSoft(HandsetSoft soft) 32 { 33 this.soft = soft; 34 } 35 36 // 运行 37 public abstract void Run(); 38 } 39 40 // 手机品牌N 41 class HandsetBrandN : HandsetBrand 42 { 43 public override void Run() 44 { 45 soft.Run(); 46 } 47 } 48 49 // 手机品牌M 50 class HandsetBrandM : HandsetBrand 51 { 52 public override void Run() 53 { 54 soft.Run(); 55 } 56 } 57 58 // 客户端 59 static void Main(string[] args) 60 { 61 HandsetBrand ab; 62 ab = new HandsetBrandN(); 63 64 ab.SetHandsetSoft(new HandsetGame()); 65 ab.Run(); 66 67 ab.SetHandsetSoft(new HandsetAddressList()); 68 ab.Run(); 69 70 ab = new HandsetBrandM(); 71 72 ab.SetHandsetSoft(new HandsetGame()); 73 ab.Run(); 74 75 ab.SetHandsetSoft(new HandsetAddressList()); 76 ab.Run(); 77 }

浙公网安备 33010602011771号