C # Design Patterns-Observer patterns (Observer pattern)

Source: Internet
Author: User

I. Overview
In software design work there is a dependency between objects, and when an object changes, all objects that depend on it need to be notified. If the design is not good, it is easy to cause the coupling between the object is too high, difficult to cope with the change. Using the Observer pattern reduces the dependency between objects and achieves this in a loosely coupled manner.
Second, the Observer pattern
The Observer pattern defines a one-to-many dependency between objects, and when an object's state changes, all objects that depend on it are notified and updated automatically. The structure diagram is as follows:

Subject knows all of its observers and provides an interface for observers to register and delete subscriptions.
Observer defines an update interface for objects that need to be notified when a target is changed.
The ConcreteSubject implements the subject interface, which sends a notification to the concreteobserver that relies on it when the state is changed.
CONCRETEOBSERVER implementation of observer update interface, so that they can be based on the ConcreteSubject state of the different and make corresponding changes.
The observer pattern is divided into two types: Push mode and pull mode. Push mode is when there is a notification, the dependent object information is passed to all observers in the form of parameters, while the pull mode notification method itself does not take any parameters, it is from the observer himself to the dependent object to retrieve the relevant information. In push mode, all observers get all the information of the dependent object through parameter passing, and the coupling between the dependent objects is lower, but the information required by "On demand" is not realized. The pull mode is simply to inform the observer, as to whether to extract the information of the dependent object is the Observer's own thing, so as to achieve "on-demand", but often in the concreteobserver to save a concretesubject reference, The coupling with the ConcreteSubject has also been strengthened.
The subject of the observer pattern generally needs to provide an interface for observers to register and delete subscriptions, but in the. NET, it is often possible to take advantage of the characteristics of events and delegates to implement the observer pattern, which is a more elegant scenario.
Iii. examples
We now use events to implement the Observer pattern. We design a simple example of a credit card consumption that requires a debit to the user's account while the user is being charged, as well as an SMS alert.
The credit card class is defined first, and when the consumption amount changes, it triggers the Notify method to notify all observers of the object.

1 Public     class Creditcard:eventargs 2     {3         private float _spendamount, 4 public         event EVENTHANDLER<CR Editcard> Spendmoney; 5  6 Public         float Spendamount 7         {8             get 9             {Ten                 return _spendamount;11             }12             set13             {                 _spendamount = value;15                 Notify ();             }17         }18         private void Notify ()         {21             if (Spendmoney! = null)                 { Spendmoney (this, this);             }25         }26     }

Then define the Observer interface and enable the user account class and SMS alert class to implement this interface, where the Update method signature of these two concreteobserver classes must be identical to the events Sendmoney in CreditCard. Otherwise, you cannot register to CreditCard.

1 Public    Interface iobserver<t> 2     {3         void Update (Object sender, T e); 4     } 5  6 Public     class Smsnotify:iobserver<creditcard> 7     {8 public         void Update (Object sender, CreditCard e) 9         {Ten             Cons Ole. WriteLine ("Sms notify. Spend {0} ", E.spendamount),         }12}13, public     class account:iobserver<creditcard>15     {16         Private float _accountamount;17 public account         (float accountamount)         {             _accountamount = ACCOUNTAMOUNT;21         }22-Public         void Update (Object sender, CreditCard e),         {             _accountamount + = e. Spendamount;26             Console.WriteLine ("account amount is {0}", _accountamount);         }28     }

Finally, look at the client call.

1     static void Main (string[] args) 2     {3         CreditCard CreditCard = new CreditCard (); 4         smsnotify SMS = new SMSN Otify (); 5 Account Account         = new account, 6         Creditcard.spendmoney + = account. Update;7         Creditcard.spendmoney + = SMS. Update;8         Creditcard.spendamount = 200;9     

C # Design Patterns-Observer patterns (Observer pattern)

Related Article

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.