Design Pattern-Observer mode (OBSERVER)

Source: Internet
Author: User

1 Observer pattern: There are observers, then there must be a corresponding observer, the essence of the observer pattern can be summed up-when the observed changes, can timely inform the observation value, the observer can be notified after the corresponding treatment.

2 Sample Code

2.1 Defines the Observer interface, the method is that when the observer receives the notice of the Observer, the corresponding processing will be made

Obverser {change ();}

2.2 Definition of two observers

Observer1 Obverser {change () {System.    println (); }}
Observer2 Obverser {change () {System.    println (); }}

2.3 Define the observer (since to be notified, there should be a way to save the object to be notified and to add a delete notification object, which can be extended; method of notification)

Subject {notification ();    Add (Obverser obverser);        Del (Obverser Obverser); Opreation ();}

2.4 The implementation class of the observer (why it is defined here as an abstract class, because it is possible that different observers will notify different observers)

Msubject Subject {vector<obverser> =vector<obverser> ();        Notification () {enumeration<obverser> enumeration=. elements ();        (Enumeration.hasmoreelements ())        {enumeration.nextelement (). change ();    }} Add (Obverser obverser) {. Add (Obverser);    } del (Obverser obverser) {. Remove (Obverser); }}

2.5 Specific one of the observed

Msubsubject Msubject {opreation () {System..        println ();    Notification (); }}

2.6 Testing

Main {main (string[] args) {Subject subject=msubsubject ();        Subject.add (Observer1 ());        Subject.add (Observer2 ());    Subject.opreation (); }}

2.7 Test Results




Design Pattern-Observer mode (OBSERVER)

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: 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.