Java design pattern-Observer Pattern

Source: Internet
Author: User

Basic Concepts

Observer mode: defines a one-to-many dependency between objects. When the State of an object changes, all objects dependent on it are notified and updated automatically. This mode is most commonly used in the familiar event-driven model. Event responses in the VC and Android interfaces are implemented based on the observer mode.

Meaning of observer Mode

Next I will explain my understanding of the observer mode. In fact, this mode is a very common mode in our daily work. You may have used it before and are not aware of it.

The observer mode is mainly for one-to-many data updates. Simply put, an element in the system updates the data, and several elements use the data of this element. When the data object is updated, it is necessary to notify other objects that use the data so that all objects can be updated.

The standard observer object is a one-to-many relationship, but we all know that the design pattern is flexible and often needs to be deformed when we use it. Modify the existing standard mode to meet the design requirements.

In our actual application, we will also encounter one-to-one or multiple-to-one situations. One-to-one means that a target corresponds to an observer. Multiple-to-one means that multiple targets correspond to one observer.

Class diagram:

Instance 1

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.

Observer. java

/**

* Observer (Observer, Observer ):

* Defines an update interface for objects that need to be notified when the target changes.

*@ AuthorAndy. Chen

*

*/

Public interfaceObserver {

Public voidUpdate ();

}

Subject. java

/**

* Subject (target, Subject): defines the target object or the object to be observed.

* The target knows its observer. Multiple observers can observe the same object.

* Provides interfaces for registering and deleting observer objects.

*@ AuthorAndy. Chen

*

*/

Public interfaceSubject {

Public voidAttach (Observer mObserver );

Public voidDetach (Observer mObserver );

Public voidNotice ();

}

Teacher. java

ImportJava. util. Vector;

/**

* ConcreteSubject (the specific target, Teacher) is the actual object to be observed.

* Stores related states into various ConcreteObserve objects.

* When his status changes, a notification is sent to each of his observers.

*@ AuthorAndy. Chen

*

*/

Public classTeacherImplementsSubject {

PrivateStringphone;

Private VectorStudents;

PublicTeacher (){

Phone = "";

Students =NewVector();

}

@ Override

Public voidAttach (Observer mObserver ){

Students. add (mObserver);

}

@ Override

Public voidDetach (Observer mObserver ){

Students. remove (mObserver );

}

@ Override

Public voidNotice (){

For(IntI = 0; I

(Observer) students. get (I). update ();

}

}

PublicStringgetPhone (){

ReturnPhone;

}

Public voidSetPhone (String phone ){

This. Phone = phone;

Notice ();

}

}

Observer object

Student. java

/**

* ConcreteObserver (Specific observer, Student): is the actual observer object.

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

*@ AuthorAndy. Chen

*

*/

Public classStudentImplementsObserver {

PrivateStringname;

PrivateStringphone;

PrivateTeachermTeacher;

PublicStudent (String name, Teachert ){

This. Name = name;

MTeacher = t;

}

Public voidShow (){

System.Out. Println ("Name:" + name + "\ nTeacher 'sphone:" + phone );

}

@ Override

Public voidUpdate (){

Phone = mTeacher. getPhone ();

}

}

Test class

Test. java

ImportJava. util. Vector;

Public classTest {

Public static voidMain (String [] args ){

VectorStudents =NewVector();

Teacher t =NewTeacher ();

For(IntI = 0; I <10; I ++ ){

Student st =NewStudent ("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(IntI = 0; I <3; I ++)

(Student) students. get (I). show ();

T. setPhone ("87654321 ");

For(IntI = 0; I <3; I ++)

(Student) students. get (I). show ();

}

}

Instance 2

Click Event of View in Android

OnClickListener. java

Public interfaceOnClickListener {

VoidOnClick (TextView v );

}

TextView. java

Public classTextView {

OnClickListener l;

PublicTextView (){

}

// Simulate click

Public voidClick (){

L. onClick (This);

}

Public voidSetOnClickListener (OnClickListenerL ){

This. L = l;

}

}

Test. java

Public classTest {

Public static voidMain (String [] args ){

TextView TV =NewTextView ();

TV. setOnClickListener (NewOnClickListener (){

@ Override

Public voidOnClick (TextView v ){

System.Out. Println (v. getClass (). getName () + "clicked ");

}

});

TV. click ();

}

}

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.

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.