Design Pattern 7-Observer pattern (observer)

Source: Internet
Author: User

[1] basic concepts

The observer mode 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. The observer mode is also called the publish/subscribe mode.

[2] Simple Analysis

Let's take a look at the UML structure of the design pattern.


Is the structure diagram of the observer mode, which allows us to describe more conveniently:

Subject Class, which stores all references to the observer object in one aggregation. Each topic can have any number of observations. Abstract topics provide an interface for adding and deleting observed objects.

The observer class is an abstract observer. It defines an interface for all the specific observers and updates itself when receiving notifications from the topic.

Concretesubject class. The status of a subject is stored in a specific observer object. When the internal status of a subject changes, a notification is sent to all registered observers.

Concreteobserver class, a specific observer, implements the update interface required by the abstract observer role, so that the status of the observer can be consistent with the status of the topic.

[3] How to Use Java to implement this mode

The following is a simple example to show this mode. First, let's look at the code structure:


In this example, a teacher has a phone number and students need to know the phone number of the teacher so that they can call the phone number when appropriate. In this combination, the teacher is a subject, and the student is the observer who needs to know the information. When the teacher's phone number changes, the student is notified and the corresponding phone number is updated.

3.1
Create a subject class first:

Package com. andyidea. patterns. Subject; import com. andyidea. patterns. Observer. Observer;/*** subject (target, subject): * The target knows its observer. Multiple observers can observe the same object. * Provides interfaces for registering and deleting observer objects. * @ Author Andy. Chen **/public interface subject {public void attach (Observer mobserver); Public void detach (Observer mobserver); Public void notice ();}

3.2
Create an observer class:

Package com. andyidea. patterns. Observer;/*** observer (Observer, observer): * defines an update interface for objects that need to be notified when the target changes. * @ Author Andy. Chen **/public interface observer {public void Update ();}

3.3
Create a concretesubject class:

Package COM. andyidea. patterns. concretesubject; import Java. util. vector; import COM. andyidea. patterns. observer. observer; import COM. andyidea. patterns. subject. subject;/*** concretesubject (specific target, teacher) * stores related states into various concreteobserve objects. * When his status changes, a notification is sent to each of his observers. * @ Author Andy. chen **/public class teacher implements subject {private string phone; private vector students; public teacher () {Phone = ""; students = new vector ();} @ overridepublic void attach (Observer mobserver) {students. add (mobserver) ;}@ overridepublic void detach (Observer mobserver) {students. remove (mobserver) ;}@ overridepublic void notice () {for (INT I = 0; I <students. size (); I ++) {(observer) students. get (I )). update () ;}} Public String getphone () {return phone;} public void setphone (string phone) {This. phone = phone; notice ();}}

3.4
Create a concreteobserver class:

Package COM. andyidea. patterns. concreteobserver; import COM. andyidea. patterns. concretesubject. teacher; import COM. andyidea. patterns. observer. observer;/*** concreteobserver (Specific observer, student): * maintain a reference pointing to the concretesubject object. * Storage-related statuses, which should be consistent with the target status. * The Observer update interface is implemented to ensure that its status is consistent with that of the target. * @ Author Andy. chen **/public class student implements observer {private string name; private string phone; private teacher mteacher; Public student (string name, teacher t) {This. name = Name; mteacher = T;} public void show () {system. out. println ("name:" + name + "\ nteacher 'sphone:" + phone) ;}@ overridepublic void Update () {Phone = mteacher. getphone ();}}

3.5
Client test class: observerclient. java.

Package COM. andyidea. patterns. client; import Java. util. vector; import COM. andyidea. patterns. concreteobserver. student; import COM. andyidea. patterns. concretesubject. teacher;/*** observer (observer) mode test class * @ author Andy. chen **/public class observerclient {public static void main (string [] ARGs) {vector students = new vector (); teacher T = new teacher (); for (INT I = 0; I <10; I ++) {student ST = new student ("Andy . Chen "+ I, T); students. Add (ST); T. Attach (ST);} system. Out. println (" Welcome to Andy. Chen blog! "+" \ N "+" Observer patterns. "+" \ n "+" ----------------------------- "); T. setphone ("12345678"); For (INT I = 0; I <3; I ++) (student) students. get (I )). show (); T. setphone ("87654321"); For (INT I = 0; I <3; I ++) (student) students. get (I )). show ();}}

[4] the program running result is as follows:

Welcome to Andy.Chen Blog!Observer Patterns.-------------------------------Name:Andy.Chen0Teacher'sphone:12345678Name:Andy.Chen1Teacher'sphone:12345678Name:Andy.Chen2Teacher'sphone:12345678Name:Andy.Chen0Teacher'sphone:87654321Name:Andy.Chen1Teacher'sphone:87654321Name:Andy.Chen2Teacher'sphone:87654321

Conclusion: When does the observer mode apply?

1. When an abstract model has two aspects, one of which depends on the other. Encapsulate the two in an independent object so that they can change and reuse them independently.

2. When changing an object, you need to change other objects at the same time without knowing the specific number of objects to be changed.

3. When an object must notify other objects, it cannot assume who the other objects are. In other words, you do not want these objects to be tightly coupled. Let both sides of coupling depend on abstraction, rather than on specifics.


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.