结构型设计模式之桥接模式(Bridge)
结构 |
![]() |
意图 | 将抽象部分与它的实现部分分离,使它们都可以独立地变化。 |
适用性 |
|
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 using System; 2 3 class Abstraction 4 { 5 protected Implementation impToUse; 6 7 public void SetImplementation(Implementation i) 8 { 9 impToUse = i; 10 } 11 12 virtual public void DumpString(string str) 13 { 14 impToUse.DoStringOp(str); 15 } 16 } 17 18 class DerivedAbstraction_One : Abstraction 19 { 20 override public void DumpString(string str) 21 { 22 str += ".com"; 23 impToUse.DoStringOp(str); 24 } 25 } 26 27 class Implementation 28 { 29 public virtual void DoStringOp(string str) 30 { 31 Console.WriteLine("Standard implementation - print string as is"); 32 Console.WriteLine("string = {0}", str); 33 } 34 } 35 36 class DerivedImplementation_One : Implementation 37 { 38 override public void DoStringOp(string str) 39 { 40 Console.WriteLine("DerivedImplementation_One - don't print string"); 41 } 42 } 43 44 class DerivedImplementation_Two : Implementation 45 { 46 override public void DoStringOp(string str) 47 { 48 Console.WriteLine("DerivedImplementation_Two - print string twice"); 49 Console.WriteLine("string = {0}", str); 50 Console.WriteLine("string = {0}", str); 51 } 52 } 53 54 /// <summary> 55 /// Summary description for Client. 56 /// </summary> 57 public class Client 58 { 59 Abstraction SetupMyParticularAbstraction() 60 { 61 // we localize to this method the decision which abstraction and 62 // which implementation to use. These need to be decided 63 // somewhere and we do it here. All teh rest of the client 64 // code can work against the abstraction object. 65 Abstraction a = new DerivedAbstraction_One(); 66 a.SetImplementation(new DerivedImplementation_Two()); 67 return a; 68 } 69 70 public static int Main(string[] args) 71 { 72 Client c = new Client(); 73 Abstraction a = c.SetupMyParticularAbstraction(); 74 75 // From here on client code thinks it is talking to the 76 // abstraction, and will not need to be changed as 77 // derived abstractions are changed. 78 79 // more client code using the abstraction goes here 80 // . . . 81 a.DumpString("Clipcode"); 82 83 return 0; 84 } 85 }