. Net Observer mode (Observer)

Source: Internet
Author: User
Directory
  1. Definition
  2. UML
  3. Participants
  4. Example

 

Definition:

Defines a one-to-many dependency between objects so that when the status of an object changes, all objects dependent on it are notified and automatically refreshed.

 

UML:

 

Participants:

Topic role:

The topic role stores all references to the observed objects in one aggregation. Each topic can have any number of observers. A topic provides an interface to add and delete observer objects. A Topic role is also called an Observable role.

The specific topic (ConcreteSubject) role:

The specific class that implements the role interface of the topic, stores the relevant status into the specific observer object, and sends a notification to all registered observers when the internal status of the specific topic changes. A topic role is also called a Concrete Observable ).

Observer (Observer) role:

Define an interface for all the specific observers and update themselves when receiving notifications from the topic. This interface is called the update interface. Abstract observer roles are generally implemented using an abstract class or an interface. In this schematic implementation, the Update Interface contains only one method (that is, the Update () method). This method is called the Update method.

ConcreteObserver role:

The observer role implements the update interface required by the observer role so that the status of the observer can be consistent with that of the topic. If necessary, the observer role can save a reference pointing to a specific topic object. A specific observer role is usually implemented by a specific subclass.

 

Example:
Code using System; using System. collections. generic; namespace DoFactory. gangOfFour. observer. structural {// <summary> // MainApp startup class for Structural // Observer Design Pattern. /// </summary> class MainApp {// <summary> // Entry point into console application. /// </summary> static void Main () {// Configure Observer pattern ConcreteSubject s = new ConcreteSubject (); s. attach (new ConcreteObserver (s, "X"); s. attach (new ConcreteObserver (s, "Y"); s. attach (new ConcreteObserver (s, "Z"); // Change subject and modify y observers s. subjectState = "ABC"; s. Y (); // Wait for user Console. readKey ();}} /// <summary> // The 'subobject' abstract class // </summary> abstract class Subject {private List <Observer> _ observers = new List <Observer> (); public void Attach (Observer observer) {_ observers. add (observer);} public void Detach (Observer observer) {_ observers. remove (observer);} public void Policy () {foreach (Observer o in _ observers) {o. update () ;}}/// <summary> // The 'cretesubobject' class /// </summary> class ConcreteSubject: Subject {private string _ subjectState; // Gets or sets subject state public string SubjectState {get {return _ subjectState;} set {_ subjectState = value ;}}} /// <summary> // The 'observer' abstract class // </summary> abstract class Observer {public abstract void Update ();} /// <summary> // The 'concreteobserver' class // </summary> class ConcreteObserver: Observer {private string _ name; private string _ observerState; private ConcreteSubject _ subject; // Constructor public ConcreteObserver (ConcreteSubject subject, string name) {this. _ subject = subject; this. _ name = name;} public override void Update () {_ observerState = _ subject. subjectState; Console. writeLine ("Observer {0}'s new state is {1}", _ name, _ observerState );} // Gets or sets subject public ConcreteSubject Subject {get {return _ subject;} set {_ subject = value ;}}}}

Output

Observer X's new state is ABC
Observer Y's new state is ABC
Observer Z's new state is ABC

Practical Application

Code using System; using System. collections. generic; namespace DoFactory. gangOfFour. observer. realWorld {/// <summary> /// MainApp startup class for Real-World // Observer Design Pattern. /// </summary> class MainApp {// <summary> // Entry point into console application. /// </summary> static void Main () {// Create IBM stock and attach investors IBM = new IBM ("ibm", 120.00); IBM. attach (new Inve Stor ("Sorros"); ibm. attach (new Investor ("Berkshire"); // Fluctuating prices will handle Y investors ibm. price = 120.10; ibm. price = 121.00; ibm. price = 120.50; ibm. price = 120.75; // Wait for user Console. readKey () ;}/// <summary> // The 'subobject' abstract class // </summary> abstract class Stock {private string _ symbol; private double _ price; private List <IInvestor> _ investors = new List <II Nvestor> (); // Constructor public Stock (string symbol, double price) {this. _ symbol = symbol; this. _ price = price;} public void Attach (IInvestor investor) {_ investors. add (investor);} public void Detach (IInvestor investor) {_ investors. remove (investor);} public void Policy () {foreach (IInvestor investor in _ investors) {investor. update (this);} Console. writeLine ("");} // Gets or sets the pric E public double Price {get {return _ price;} set {if (_ price! = Value) {_ price = value; y () ;}}// Gets the symbol public string Symbol {get {return _ symbol ;}}} /// <summary> // The 'concretesubobject' class // </summary> class IBM: Stock {// Constructor public IBM (string symbol, double price ): base (symbol, price) {}}/// <summary> // The 'observer' interface // </summary> interface IInvestor {void Update (Stock stock );} /// <summary> // The 'concreteobserver' class // </summary> class Investor: IInvestor {private string _ name; private Stock _ stock; // Constructor public Investor (string name) {this. _ name = name;} public void Update (Stock stock) {Console. writeLine ("Notified {0} of {1}'s" + "change to {2: C}", _ name, stock. symbol, stock. price) ;}// Gets or sets the stock public Stock {get {return _ stock;} set {_ stock = value ;}}}}

Output

Notified Sorros of IBM's change to $120.10
Notified Berkshire of IBM's change to $120.10
Notified Sorros of IBM's change to $121.00
Notified Berkshire of IBM's change to $121.00
Notified Sorros of IBM's change to $120.50
Notified Berkshire of IBM's change to $120.50
Notified Sorros of IBM's change to $120.75
Notified Berkshire of IBM's change to $120.75

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.