Reactive Extensions 初识

目录:

简介

示例

结论

 

在.NET 4.0中多了一个IObservable和IObserver接口。用MSDN的话说是:基于推送的通知的提供程序。相当拗口。个人理解就是属性发生变化时,订阅该属性的方法得到通知。就是观察者模式的定义。

 

示例:

现在有A和B。他们输入值后得到C。只要A和B有一个输入,C就会发生变化。

AND Gate

我用观察者模式来写 A输入了值。C发生了变化:

 public enum Bit
    {
        Low = 0,
        High = 1
    }
 
public interface IInput
    {
        void SetValue(Bit bit);
    }
    public interface IGate
    {
        void Register(IInput input);
  // void UnRegister(IInput input);
    }
    public class Gate : IGate
    {
        private static Hashtable _container = new Hashtable();

        public void Register(IInput input)
        {
            _container.Add(input, input);
        }

       protected void NotifyProperty(Bit bit)
        {
            foreach (IInput item in _container.Keys)
            {
                item.SetValue(bit);
            }
        }
    }
    public class ObserverC:IInput
    {
        public void SetValue(Bit bit)
        {
            Console.WriteLine(bit);
        }
    }
    public class ObserverA : Gate
    {
        private string _name;
        public string Name
        {
            get { return _name; }
            set { _name = value;base.NotifyProperty(Bit.Low); }
        }
    }


在Main()中调用

ObserverA a=new ObserverA();
ObserverC c = new ObserverC();
Gate gate= new Gate();
gate.Register(c);
a.Name="hello";

结果输出 Low;

 

那用IObservable来写会简化很多,这时需要引入System.Reactive.dll

public class Input
    {
        private Subject<Bit> valueStream = new Subject<Bit>();
        public IObservable<Bit> Value { get { return valueStream; } }
        public void SetValue(Bit value)
        {
            valueStream.OnNext(value);
        }
    }
    public class Gate
    {
        private IObservable<Bit> _subject;

        public Gate(IObservable<Bit> x, IObservable<Bit> y)
        {
            _subject = x.CombineLatest(y, Calculate);
        }

        protected virtual Bit Calculate(Bit arg1, Bit arg2)
        {
            return Bit.Low;
        }

        public IObservable<Bit> Value { get { return _subject; } }

    }

    public enum Bit
    {
        Low = 0,
        High = 1
    }

    public class AndGate : Gate
    {
        public AndGate(IObservable<Bit> x, IObservable<Bit> y)
            : base(x, y)
        { }

        protected override Bit Calculate(Bit arg1, Bit arg2)
        {
            return (arg1 == Bit.High && arg2 == Bit.High) ? Bit.High : Bit.Low;
        }
    }


在Main中:
Input a1 = new Input();
Input a2 = new Input();
AndGate andGate = new AndGate(a1.Value, a2.Value);
andGate.Value.Subscribe(x => Console.WriteLine(x));
a1.SetValue(Bit.High);
a2.SetValue(Bit.High);

结果:High

 

结论:IObservable demo中Subject类似于观察者模式demo中Hashtable。Subscrible类似于NotifyProperty方法。

posted @ 2012-06-07 21:08  Lee's Blog  阅读(608)  评论(2编辑  收藏  举报