设计模式——中介者模式
名称 | Mediator |
结构 | |
意图 | 用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。 |
适用性 |
|
Code Example |
1// Mediator 2 3// Intent: "Define an object that encapsulates how a set of objects interact. 4// Mediator promotes loose coupling by keeping objects from referring to each 5// other explicitly, and it lets you vary their interaction independently." 6 7// For further information, read "Design Patterns", p273, Gamma et al., 8// Addison-Wesley, ISBN:0-201-63361-2 9 10/* Notes: 11 * Consider a mediator as a hub, which objects that need to talk - 12 * but do not wish to be interdependent - can use. 13 */ 14 15namespace Mediator_DesignPattern 16{ 17 using System; 18 19 class Mediator 20 { 21 private DataProviderColleague dataProvider; 22 private DataConsumerColleague dataConsumer; 23 public void IntroduceColleagues(DataProviderColleague c1, DataConsumerColleague c2) 24 { 25 dataProvider = c1; 26 dataConsumer = c2; 27 } 28 29 public void DataChanged() 30 { 31 int i = dataProvider.MyData; 32 dataConsumer.NewValue(i); 33 } 34 } 35 36 class DataConsumerColleague 37 { 38 public void NewValue(int i) 39 { 40 Console.WriteLine("New value {0}", i); 41 } 42 } 43 44 class DataProviderColleague 45 { 46 private Mediator mediator; 47 private int iMyData=0; 48 public int MyData 49 { 50 get 51 { 52 return iMyData; 53 } 54 set 55 { 56 iMyData = value; 57 } 58 } 59 public DataProviderColleague(Mediator m) 60 { 61 mediator = m; 62 } 63 64 public void ChangeData() 65 { 66 iMyData = 403; 67 68 // Inform mediator that I have changed the data 69 if (mediator != null) 70 mediator.DataChanged(); 71 } 72 } 73 74 /// <summary> 75 /// Summary description for Client. 76 /// </summary> 77 public class Client 78 { 79 public static int Main(string[] args) 80 { 81 Mediator m = new Mediator(); 82 DataProviderColleague c1 = new DataProviderColleague(m); 83 DataConsumerColleague c2 = new DataConsumerColleague(); 84 m.IntroduceColleagues(c1,c2); 85 86 c1.ChangeData(); 87 88 return 0; 89 } 90 } 91} 92 93 |