本文直接使用.net 提供的接口来实现Observer Pattern(IObserver,IObservable)。 也可以自定义接口。
如何实现:
1.定义一个Subject Provider 类。
需要实现Subscribe()。
2.定义一个Observer 类。
需要实现OnNext() 用来输出信息或者要执行的操作。
需要实现OnComplete() 完成后要执行的操作。
需要实现OnError() 万一出现错误,输出错误信息。
下面提供一个我能想到的最简单的Sample,忽略所有其它细节,只关注Observer pattern。
Sample:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestObserverPatternSimplestSample { class Program { static void Main(string[] args) { MySubjectProvider provider=new MySubjectProvider(); MyObserver observer1=new MyObserver("observer1"); provider.Subscribe(observer1); // provider.Subscribe(observer1).Dispose(); MyObserver observer2 = new MyObserver("observer2"); provider.Subscribe(observer2); provider.NotifyObserver("hello"); Console.ReadLine(); } } public class MyObserver : IObserver<string> { private IDisposable _disposable; private string _name; public MyObserver(string name) { this._name = name; } public string Name { get { return this._name; } } public void OnCompleted() { Console.WriteLine("observer complete event. "); } public void OnNext(string msg) { Console.WriteLine("the {0} is received msg {1} from subject provider.",Name, msg); } public void OnError(Exception ex) { Console.WriteLine("error occured"); } public void Unsubscribe(IObservable<string> provider ) { // provider. } } public class MySubjectProvider : IObservable<string> { public List<IObserver<string>> observers=new List<IObserver<string>>(); public IDisposable Subscribe(IObserver<string> observer) { if(!observers.Contains(observer)) observers.Add(observer); return new UnSubscribe(observers,observer); } public class UnSubscribe : IDisposable { private List<IObserver<string>> _observers; private IObserver<string> _observer; public UnSubscribe(List<IObserver<string>> observers,IObserver<string> observer ) { this._observers = observers; this._observer = observer; } public void Dispose() { if (_observer != null) { _observers.Remove(_observer); } } } public void NotifyObserver(string msg) { foreach (var observer in observers) { observer.OnNext(msg); } } } }