标签:
观察者模式定义了对象之间的一对多依赖,这样一来,当一个对象改变状态时,他的所有依赖着都会收到通知并自动更新。
设计原则 为了交互对象之间的松耦合设计而努力
1 using System; 2 using System.Collections; 3 using System.Collections.Generic; 4 using System.Linq; 5 using System.Text; 6 using System.Threading.Tasks; 7 8 namespace ObserverPattern 9 { 10 11 //创建发送者的接口 12 public interface IObserver 13 { 14 void update(float temp, float humidity, float pressure); 15 } 16 //主题接口,供注册和解除监听 17 public interface ISubject 18 { 19 void registerObserver(IObserver o); 20 void removeObserver(IObserver o); 21 void notifyObserver(); 22 } 23 //显示接口 24 public interface IDisplayElement 25 { 26 void display(); 27 } 28 29 //源,实现监听者的添加删除以及发送消息 30 public class WeatherData : ISubject 31 { 32 public ArrayList observers; 33 public float temperature; 34 public float humidity; 35 public float pressure; 36 37 38 public WeatherData() 39 { 40 observers = new ArrayList(); 41 } 42 43 44 public void registerObserver(IObserver o) 45 { 46 observers.Add(o); 47 } 48 49 public void removeObserver(IObserver o) 50 { 51 observers.Remove(o); 52 } 53 //给每个监听者发送消息 54 public void notifyObserver() 55 { 56 for (int i = 0; i < observers.Count; i++) 57 { 58 (observers[i] as IObserver).update(temperature, humidity, pressure); 59 } 60 } 61 62 //触发消息 63 public void measurementsChanged() 64 { 65 notifyObserver(); 66 } 67 //设置消息值 68 public void setMeasurements(float temperature, float humidity, float pressure) 69 { 70 this.temperature = temperature; 71 this.humidity = humidity; 72 this.pressure = pressure; 73 74 measurementsChanged(); 75 } 76 77 } 78 79 //监听者之一 80 public class CurrentConditionsDisplay : IObserver, IDisplayElement 81 { 82 83 84 85 public float temperature; 86 public float humidity; 87 public float pressure; 88 private ISubject WeatherData; 89 public CurrentConditionsDisplay(ISubject WeatherData) 90 { 91 this.WeatherData = WeatherData; 92 WeatherData.registerObserver(this);//把自己注册进去监听 93 } 94 95 //weather会调用这个方法 96 public void update(float temp, float humidity, float pressure) 97 { 98 this.temperature = temp; 99 this.humidity = humidity; 100 this.pressure = pressure; 101 display(); 102 } 103 //显示 104 public void display() 105 { 106 Console.WriteLine("Current conditions:" + temperature + "F degrees and " + humidity + "humidity"); 107 } 108 109 110 } 111 }
标签:
原文地址:http://www.cnblogs.com/kaysily/p/4590536.html