Design Pattern-Observer Pattern

Source: Internet
Author: User

Definition: defines a one-to-many dependency, allowing multiple observer objects to listen to a topic object at the same time. When the status of this topic object changes, it notifies all observer objects so that they can automatically update themselves.

Structure:


Sample Code:

Public interface observer {public void Update ();} public class subject {private list <observer> Observers = new arraylist <observer> (); Public void attach (Observer observer) {observers. add (observer);} public void detach (Observer observer) {observers. remove (observer);} public void Policy1 () {for (Observer observer: Observers) {observer. update () ;}} public class concretesubject extends subject {private string subjectstate; Public String getsubjectstate () {return subjectstate;} public void setsubjectstate (string subjectstate) {This. subjectstate = subjectstate;} public class concreteobserver implements observer {private string name; private string observerstate; private concretesubject subject; Public concreteobserver (concretesubject, string name) {This. subject = subject; this. name = Name ;}@ overridepublic void Update () {// todo auto-generated method stubobserverstate = subject. getsubjectstate (); system. out. println ("Observer" + name + "status is" + observerstate );}}
The client code is as follows:

public class Client {public static void main(String[] args) {ConcreteSubject s = new ConcreteSubject();s.attach(new ConcreteObserver(s, "x"));s.attach(new ConcreteObserver(s, "Y")); s.attach(new ConcreteObserver(s, "Y"));s.setSubjectState("ABC");s.notify1();}}

Running result:

The status of the observer X is ABC.

The y status of the observer is ABC.

The y status of the observer is ABC.



Design Pattern-Observer Pattern

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.