24-Day Learning Design pattern------Observer pattern

Source: Internet
Author: User

First, the Observer pattern

1. Observer mode Observer

The Observer pattern defines a one-to-many dependency that allows multiple observer objects to listen to a Subject object at the same time.

When the subject object changes in state, all observer objects are notified, allowing them to automatically update themselves.

2, the use of the Observer mode

(1) When an abstract model has two facets , One aspect depends on the other. The two are encapsulated in separate objects so that they can be individually changed and reused.

(2) When a change to an object needs to change other objects at the same time , it is not known how many objects need to be changed.

(3) When an object must notify other objects, it cannot assume that other objects are who. In other words , you don't want these objects to be tightly coupled.

3, the composition of the Observer pattern

   Abstract Theme Roles : All references to the Observer object are saved in a collection, and each abstract theme role can have any number of observers. Abstract topics provide an interface that can add and remove observer roles. It is generally implemented with an abstract class and interface.

  Abstract Observer Role : Define an interface for all specific observers and update yourself when you get notifications for a topic.

  specific topic role : Notifies all registered observers when the internal state of a specific topic changes. A specific theme role is typically implemented with a subclass.

  specific Observer role : This role implements the update interfaces required by the abstract observer role in order to reconcile the state of itself with the state of the topic. Typically implemented with a subclass. If necessary, the specific observer role can save a reference to a specific topic role.

Ii. Examples of Use

Here simulates the function of the American network, when you go to the United States online registration of an account, whenever there is a new group purchase, will send mail to your mailbox. Here, I changed it, and whenever there was a new food, it was sent to the user

/*** file Name: observermethod.java* Description: Viewer mode explanation * Creator: Lin Bingwen * Date: 2015.1.27**/package linbingwen;import java.util.arraylist;/*        Abstract target class */interface subject{/* Registered Observer */public void Registerobserver (Observer obj);    /* Delete Observer */public void Removeobserver (Observer obj); /* Notify all observations */public void notifyallobservers (String food);} /* Abstract Observer class */interface Observer {public void update (String food); /* Specific target class */class Realsubject implements Subject{private arraylist<observer> userlist=new arraylist<observer > ();//used to store the Observer private arraylist<string> food=new arraylist<string> ();//used to store what food @overridepublic Void Registerobserver (Observer obj) {userlist.add (obj);}    @Overridepublic void Removeobserver (Observer obj) {userlist.remove (obj);} @Overridepublic void Notifyallobservers (String food) {for (Observer obj:userlist) {obj.update;}}}        Class Realobserver implements observer{private String name;//used to save the person's name//to construct the Observer public Realobserver (String name) { THIS.name = name; }@overridepublic void Update (String food) {System.out.println ("notification" +name+ "+food+" can be eaten today);}} public class Observermethod {public static void main (string[] args) {Subject meituwang=new realsubject ();//This is the group network// Generate three observers Observer Obj1=new realobserver ("Little Red"), Observer obj2=new realobserver ("Lourdes"); Observer obj3=new realobserver ("Bing" );//Registration of three observers meituwang.registerobserver (OBJ1); Meituwang.registerobserver (OBJ2); Meituwang.registerobserver (OBJ3);//Inform three observers that there is new food to eat meituwang.notifyallobservers ("Apple"); Meituwang.notifyallobservers ("Pork"); Meituwang.notifyallobservers ("Big Rice");}}



Output Result:

Notice Little Red American network today there are apples to eat
Notify German-American network today that there are apples to eat
Inform Abimi that there are apples to eat today.


Notice Little Red American network today has pork can eat
To inform the German-American network that pork can be eaten today.
Inform Abimi that there is pork to eat today.


Notice small red American network today has big Rice can eat
Notice that the German network today has big rice to eat
Inform Abimi that there is big rice to eat today


III. Observer patterns other advantages and disadvantages

Here are some other advantages and disadvantages of the Observer pattern:
(1) Abstract coupling between the target and the observer a goal is only to know that it has a series of observers, each conforming to the simple interface of the abstract o B S e R v e R class. The target does not know which specific class any observer belongs to. This coupling between the target and the observer is abstract and minimal. Because the target and the observer are not tightly coupled, they can belong to different levels of abstraction in a system. A target object at a lower level can communicate with a higher-ranking observer and notify it, thus preserving the integrity of the system hierarchy. If the target is mixed with the observer, the resulting object will either traverse two levels (in violation of the hierarchy) or must be placed in one layer of the two layers (which may damage the hierarchy abstraction).
(2) to support broadcast communication unlike the usual request, the notification sent by the target does not need to specify its recipient. Notifications are automatically broadcast to all relevant objects that have been registered with the target object. The target object does not care how many objects are interested in itself; its sole responsibility is to inform its observers. This gives you the freedom to add and remove observers at any time. Processing or ignoring a notification depends on the observer.
(3) Unexpected updates because an observer does not know the existence of other observers, it may be ignorant of the ultimate cost of changing the target. A seemingly harmless operation on the target may result in a series of updates to the observer and those objects that depend on those observers. In addition, if the dependency criterion is defined or poorly maintained, it often causes incorrect updates, which are often difficult to capture. The simple update protocol does not provide specific details about what has changed in the target, which makes the above problem more serious. If no other protocol helps observers find out what has changed, they may be forced to try to reduce the change.

24-Day Learning 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.