C # Observer Mode example Introduction _c# tutorial

Source: Internet
Author: User
Tags data structures readline
Observer mode

Observer pattern: Defines a one-to-many dependency that allows multiple observer objects to simultaneously listen to a single Subject object that notifies all observers when the state changes. When an object changes the need to change other objects at the same time, and he does not know how many objects need to be changed, consider using the Observer pattern.

Observer Structure Chart:


Usage Scenario: The boss comes back to inform employees of the need to enter the working state.
The abstract class that defines the Observer:
Copy Code code as follows:

Abstract class Observer
{
protected string name;
protected Isubject Sub;
Public Observer (string name, Isubject sub)
{
THIS.name = name;
This.sub = Sub;
}
public abstract void Update ();
}

Watch the NBA Live colleagues:
Copy Code code as follows:

Using OO
Class Nbaobserver:observer
{
Public Nbaobserver (string name, Isubject sub)
: Base (name, sub)
{ }
public override void Update ()
{
throw new NotImplementedException ();
Console.WriteLine ("{0} {1}" closed NBA Live, continue to work!) ", Sub. Subjectstate,name);
}
}
Using Events and Delegates
Class NBAObserver2
{
private string name;
Private ISubject2 Sub;
Public NBAObserver2 (string name, ISubject2 sub)
{
THIS.name = name;
This.sub = Sub;
}
public void Closestockmarket ()
{
Console.WriteLine ("{0} {1}" closed NBA Live, continue to work!) ", Sub. Subjectstate, name);
}
}

Colleagues looking at the stock:
Copy Code code as follows:

Using OO
Class Stockobserver:observer
{
Public Stockobserver (string name, Isubject sub): Base (Name,sub)
{ }
public override void Update ()
{
throw new NotImplementedException ();
Console.WriteLine ("{0} {1}" closes stock quotes, keep working!) ", Sub. Subjectstate,name);
}
}
Using Events and Delegates
Class StockObserver2
{
private string name;
Private ISubject2 Sub;
Public StockObserver2 (string name, ISubject2 sub)
{
THIS.name = name;
This.sub = Sub;
}
public void Closenba ()
{
Console.WriteLine ("{0} {1}" closes stock quotes, keep working!) ", Sub. Subjectstate, name);
}
}

Is the subscriber, the following defines the publisher:
Copy Code code as follows:

Using OO
Interface Isubject
{
void Attach (Observer Observer);
void Detach (Observer Observer);
void Notify ();
String subjectstate
{
Get
Set
}
}
Class Boss:isubject
{
Private ilist<observer> observers = new list<observer> ();
private string action;
public void Attach (Observer Observer)
{
Observers. ADD (Observer);
}
public void Detach (Observer Observer)
{
Observers. REMOVE (Observer);
}
public void Notify ()
{
foreach (Observer o in observers)
{
O.update ();
}
}
public string Subjectstate
{
get {return action;}
set {action = value;}
}
}
Using Events and Delegates
Interface ISubject2
{
void Notify ();
String subjectstate
{
Get
Set
}
}
delegate void EventHandler ();
Class Boss2:isubject2
{
public event EventHandler Update;
private string action;
public void Notify ()
{
Update ();
}
public string Subjectstate
{
get {return action;}
set {action = value;}
}
}

Main function Call:
Copy Code code as follows:

Class Program
{
static void Main (string[] args)
{
Observer Pattern OO Implementation
Boss Huhansan = new boss ();
Stockobserver tongshi1 = new Stockobserver ("Name1", Huhansan);
Nbaobserver tonshi2 = new Nbaobserver ("Name2", Huhansan);
Huhansan. Attach (TONGSHI1);
Huhansan. Attach (TONSHI2);
Huhansan. Subjectstate = "I came back 1";
Huhansan. Notify ();
Observer Mode C # event implementation
Boss2 huhansan2 = new Boss2 ();
StockObserver2 tongshi3 = new StockObserver2 ("Name3", huhansan2);
NBAObserver2 tonshi4 = new NBAObserver2 ("Name4", huhansan2);
Huhansan2. Update + = new EventHandler (tongshi3. CLOSENBA);
Huhansan2. Update + = new EventHandler (tonshi4. Closestockmarket);
Huhansan2. Subjectstate = "I came back 2";
Huhansan2. Notify ();
Console.readkey ();
}
}

A delegate is a type of reference method, and once a method is assigned to a delegate, the delegate behaves exactly like the method. The use of a delegate method can have parameters and return values, like any other method. A delegate can be seen as an abstraction of a function, a class of functions, a delegate instance representing a specific function, and a delegate can carry multiple methods, all of which are awakened sequentially.

1 Observer mode
A simple example, such as the cat barking, the mouse running, the owner was awakened.
Before we know the Observer mode, our code might be like this.
Copy Code code as follows:

Mouse class
Class Mouse
{
public void Run ()
{
Console.WriteLine ("The Rat ran away!");
}
}
Master Class
Class Master
{
public void Wake ()
{
Console.WriteLine ("The Master woke up!");
}
}
Cat class
Class Cat
{
public void Cry ()
{
Console.WriteLine ("The Cat called!") ");
New Mouse (). Run ()//the cat barks while calling the mouse to run the method.
New Master (). Wake ()//the cat barks while calling the master's method of waking.
}
}
Class Program
{
static void Main (string[] args)
{
Cat cat = new Cat ();
Cat. Cry ();
Console.ReadLine ();
}
}

This code basically implements all the functionality. This method, however, does not use the extension in particular,
Just imagine, if the cat barks, the dog also called, that is not also in the cat called method to rejoin the dog barking method?
Or, the cat called, the owner of his wife also woke up, is not also in the cat called method to join his wife awake method?
Obviously, such code does not take advantage of maintenance or object-oriented code.
The observer model is a good solution to this problem.
The Observer pattern defines a one-to-many dependency between objects, and when an object's state changes, all objects that depend on him are notified and automatically updated. In our case, the cat and the mouse, the owner, the dog, the master his wife is a one-to-many dependency, and when the cat barks, all objects that depend on it automatically perform an action.
The realization of the observer pattern is generally composed of the following four parts.
1.ISubject Interface (abstract goal), including method Notify,register,unregister (name can be arbitrarily named)
2.Subject Class (Entity target), implement Isubject interface, generally only one
3.IObservable Interface (abstract observer).
4 Observer Class (entity observer), implement IObservable interface, generally have multiple.
"Registration-Notification-logoff" icon in Observer mode:
1. The Observer (OBSERVER) registers itself (Regiester) in the observed object (Subject) and the observed object places the observer in a container (Container). Container is generally ilist,arraylist and other data structures, holding multiple iobservable interface variables.
2. When the observed object (Subject) changes (such as the askpricechanged in the figure), all the observers (Observer) in the container (Container) are notified (Notify method), at which point the observer automatically executes certain methods.
3. When the observer does not want to continue to observe the observed, can log off (Unregiester method)
The example above is transformed into:
1.ISubject Interface:
Copy Code code as follows:

Interface Isubject
{
void Notify ()//When subject changes, the notice is observed
void Regiester (IObservable o);//Observer Registration
void Unregiester (IObservable o);//The Observer cancels registration, and the subject changes without notice.
}

2.Subject class:
Copy Code code as follows:

Class Cat:isubject
{
Private ilist<iobservable> observers = new list<iobservable> ();
public void Notify ()
{
foreach (IObservable o in observers)//notify the Observer one by one
{
O.action ();
}
}
public void Regiester (IObservable o)
{
if (o!= null | |!observers. Contains (o))
{
Observers. ADD (o);
}
}
public void Unregiester (IObservable o)
{
if (observers!= null && observers. Contains (o))
{
Observers. Remove (o);
}
}
public void Cry ()
{
Console.WriteLine ("The Cat called!") ");
Notify ();
}
}

3. IObservable Interface:
Copy Code code as follows:

Interface IObservable
{
void action ()//The Observer's action on the subject change
}

4.Observer Class (2, mouse and Master)
Copy Code code as follows:

Class Mouse:iobservable
{
public void Action ()
{
Console.WriteLine ("Rat ran!");
}
}
Class Master:iobservable
{
public void Action ()
{
Console.WriteLine ("The Master woke up!");
}
}

5. Main program
Copy Code code as follows:

Mouse Mouse = new Mouse ();
Master master = new Master ();
Cat cat = new Cat ();
Cat. Regiester (mouse);
Cat. Regiester (master);
Cat. Cry ();
Console.ReadLine ();

This implements the observer pattern by registering the dependency class in the principal class, and when the principal class changes, all dependent classes are notified. If you need to expand, say, like the dog in the example above, we can define a dog and then register the dog object in the main program with the cat. If you do not want to rely on the cat class, you can also unbind by Unregiester method.
At the same time, it also conforms to the design of high cohesion, low coupling principle.

Copy Code code as follows:

Using System;
Using System.Collections.Generic;
Using System.Text;
Namespace Sample
{
public delegate void Catcalleventhandler ();
Class Program
{
static void Main (string[] args)
{
Cat cat = new Cat ();
Mouse Mouse = new Mouse (cat);
Master master = new Master (mouse);
Cat. Call ();
}
}
Class Cat
{
public event Catcalleventhandler Catevent;
public void Call ()
{
Console.WriteLine ("Meow meow ...");
Catevent ();
}
}
Class Mouse
{
public event Catcalleventhandler MouseEvent;
Public Mouse (Cat cat)
{
Cat.catevent + = new Catcalleventhandler (this. Mouserun);
}
public void Mouserun ()
{
Console.WriteLine ("Rat Run");
MouseEvent ();
}
}
Class Master
{
Public Master (Mouse Mouse)
{
Mouse.mouseevent+=new Catcalleventhandler (this. jingxing);
}
public void jingxing ()
{
Console.WriteLine ("The Master was awakened");
}
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.