Directory:
Introduction
Example
Conclusion
In. Net 4.0, an iobservable and iobserver interfaces are added. In the words of msdn: the provision of push-based notificationsProgram. It is a massive port. In my personal understanding, the method for subscribing to this attribute is notified when the attribute changes. It is the definition of the observer mode.
Example:
Now there are a and B. They enter the value and get C. As Long As A and B have an input, C will change.
I used the observer mode to write the input value of. C has changed:
Public EnumBit {LOW = 0, high = 1}Public InterfaceIinput {VoidSetvalue (bit );}Public InterfaceIgate {VoidRegister (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 Yyproperty (bit ){ Foreach (Iinput item In _ Container. Keys) {item. setvalue (BIT );}}} Public Class Observerc: iinput { Public Void Setvalue (bit) {console. writeline (BIT );}} Public Class Observera: gate { Private String _ Name; Public String Name { Get { Return _ Name ;} Set {_ Name = Value ; Base . Yyproperty (bit. Low );}}}
Call in main ()
Observera A = new observera ();
Observerc c = new observerc ();
Gate = new gate ();
Gate. Register (C );
A. Name = "hello ";
Low Output of results;
Using iobservable will simplify the writing process. In this case, you need to introduce 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 ;}}
In Main:
Input a1 = new input ();
Input a2 = new input ();
Andgate = new andgate (a1.value, a2.value );
Andgate. value. subscribe (x => console. writeline (x ));
A1.setvalue (bit. High );
A2.setvalue (bit. High );
Result: high
Conclusion: Subject in iobservable demo is similar to hashtable in observer mode demo. Subscrible is similar to the policyproperty method.