1. Concept
The Observer pattern (sometimes called the publish-subscribe subscribe> mode, model-view view> mode, source-listener listener> mode, or slave mode) is one of the software design patterns. In this mode, a target object manages all the observer objects that are dependent on it and proactively notifies when its own state changes. This is usually done by calling the methods provided by each observer. This pattern is often used to implement an event-handling system.
2. Roles
2.1 Abstract Theme (Subject): It saves references to all observer objects in a single aggregation, each subject can have any number of observers. Abstract topics provide an interface that allows you to add and remove observer objects.
2.2 Specific topics (ConcreteSubject): deposit the relevant state into a specific observer object, and give notice to all registered observers when changes are made to the internal state of the specific subject.
2.3 Abstract Observer (Observer): Define an interface for all specific observers and update yourself when you get a topic notification.
2.4 Specific Observer (CONCRETEOBSERVER): Implements the update interface required by the abstract observer role in order to reconcile its state with the subject state.
3. Implementation of the implementation of the mandate.
Simulated scene: The cat barks, the mouse runs, the master wakes up.
3.1 Isubject Abstract
Public Delegate voidNotifyHandler ();
Public Abstract classIsubject { Public EventNotifyHandler notifyevent; protected voidNotify () {if(Notifyevent! =NULL) notifyevent (); } Public Virtual voidRun () {}}
3.2 Catsubject
Public class Catsubject:isubject { publicoverridevoid Run () { Console.WriteLine ( " the cat called ... " ); This . Notify (); } }
3.3 Observer
Public Abstract class Observer { protected Observer (isubject sub) { + = Response ; } Public Abstract void Response (); }
3.4 Mouseobserver
Public class Mouseobserver:observer { public mouseobserver (isubject sub) base(sub) { } publicoverridevoid Response () { Console.WriteLine ( " the rat ran! "); } }
3.5 Masterobserver
Public class Master2observer:observer { public master2observer (Isubject sub):Base(sub) { } Publicoverridevoid Response () { Console.WriteLine (" The master woke up .... " ); } }
3.6 Calls
var New Catsubject (); var New Mouseobserver (sub); var New
3.7 Results
C # Design Pattern-Observer pattern (using delegates)