What is the Observer pattern?
The Observer pattern defines a one-to-many dependency between objects, and when an object changes state, other dependents are notified and updated automatically.
role
- Abstract theme (Subject) role
The subject role saves all references to the observation object in a single aggregation, and each subject can have any number of observers. Abstract topics provide an interface for adding and removing observer objects, which are also called abstract Observable roles, and are generally implemented with an abstract class or an interface.
- Abstract observer (Observer) role
Define an interface for all specific observers and update yourself when you get notifications of the topic, which is called the update interface. Abstract observer roles are generally implemented with an abstract class or an interface. In this schematic implementation, the update interface contains only one method (the update () method), and this method is called the Update method.
- Specific theme (ConcreteSubject) role
The relevant state is deposited into the object of a specific observer, and all registered observers are notified when changes are made to the internal state of the specific subject. The specific subject role is also called the specific observer role (concrete Observable). A specific theme role is typically implemented with a specific subclass.
- Specific observer (CONCRETEOBSERVER) role
Stores the state of the theme from its own state. The specific viewer role implements the update interface required by the abstract observer role in order to align its state with the state of the subject. If necessary, the specific observer role can hold a reference to a specific subject object. The specific observer role is usually implemented with a specific subclass.
practicality
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.
Example Analysis
Newspapers, magazines subscriptions: 1. The newspaper's business is to publish the newspaper 2. Subscribe a newspaper to a newspaper, and if they have a new newspaper, they will send it to you. As long as you are their subscriber, you will always receive the new newspaper 3. When you don't want to read the newspaper, cancel the subscription, they will not send a new newspaper. 4. As long as the newspaper is still in operation, there will always be people subscribing to newspapers or unsubscribing from newspapers.
Publisher + Subscriber = Observer mode The newspaper is the subject, the Subscriber is the Observer, once the newspaper has a new newspaper, it will send the Subscribers 1. Create a topic interface Isubject, which includes registration, deregistration, notification of observer methods; Abstract theme Role 2. Create an Observer interface IObserver, which contains update methods for updating newspaper subscription messages;//abstract observer role 3. Create newspaper class Newspaperoffice, implement Isubject interface, re-change interface method, add news and send newspaper method; Specific theme Roles 4. Create subscriber class Subscriber, implement IObserver interface, re-update method, add subscription and unsubscribe newspaper method;//specific observer role 5. Create a test class Observerpattern
1. Abstract Themes
Package Com.pattern.subject;import Com.pattern.observer.iobserver;public Interface Isubject {public void Registerobserver (IObserver observer); public void Unregisterobserver (IObserver observer); public void Notifyobservers ();}
2. Abstract Viewer
Package Com.pattern.observer;public interface IObserver {public void Update (String mnewstitle, String mnewscontent );}
3. Specific Themes
Package Com.pattern.subject;import Java.util.arraylist;import Com.pattern.observer.iobserver;public class Newspaperoffice implements Isubject {private arraylist<iobserver> observers; Private String Newstitle; Private String newscontent; Public Newspaperoffice () {observers = new arraylist<iobserver> (); } @Override public void Registerobserver (IObserver observer) {OBSERVERS.ADD (Observer); } @Override public void Unregisterobserver (IObserver observer) {int index = OBSERVERS.INDEXOF (Observer); if (index >= 0) {observers.remove (index); }} @Override public void Notifyobservers () {for (int index = 0; index < observers.size (); index++) { IObserver observer = (iobserver) observers.get (index); Observer.update (Newstitle, newscontent); }} public void Delivernewspapers () {notifyobservers (); } public void Setnews (String mtitle,string MContent) {newstitle = Mtitle; Newscontent = mcontent; Delivernewspapers (); }}
4. Specific observers
Package Com.pattern.observer;import Com.pattern.subject.isubject;public Class Subscriber implements IObserver { Private String subscribername; Public Subscriber (String name) { subscribername = name; } public void Subscribe (Isubject msubject) { msubject.registerobserver (this); } public void Cancelsubscribe (Isubject msubject) { msubject.unregisterobserver (this); } @Override public void Update (String mnewstitle, String mnewscontent) { System.out.println ("New Newspaper to [ "+ Subscribername +"] [Title: "+ mnewstitle +"] [Content: "+ mnewscontent +"] ");} }
5. Test class
Package Com.pattern.observer;import Com.pattern.subject.newspaperoffice;public class Observerpattern {public static void Main (string[] args) { Newspaperoffice mnewspaperoffice = new Newspaperoffice (); Subscriber Zhangsan = new Subscriber ("Zhangsan"); Subscriber Lisi = new Subscriber ("Lisi"); Zhangsan.subscribe (mnewspaperoffice); Lisi.subscribe (mnewspaperoffice); Mnewspaperoffice.setnews ("Java", "Java is ok.."); Zhangsan.cancelsubscribe (mnewspaperoffice); Mnewspaperoffice.setnews ("Android", "Android is good..");} }
6. Test results
New newspaper to [Zhangsan] [Title:java] [Content:java is OK ...]
New newspaper to [Lisi] [Title:java] [Content:java is OK ...]
New newspaper to [Lisi] [title:android] [content:android is good ...]
Observer patterns in the Java API
java.util.observable//the observable class, which inherits the class from the Isubject interface function defined above itself//specific subject, public class Observable
java.util.observer//observation interface, consistent with the above-defined IObserver interface function//specific viewer implementation of the interface public interface Observer { void update ( Observable o, Object arg);}
Viewer mode in Android-broadcast mechanism
The broadcast mechanism in Android also uses the viewer mode, so long as the broadcast is registered, all the components registered for the broadcast will receive it.
Public abstract class Context {public abstract Intent registerreceiver (Broadcastreceiver receiver,intentfilter filter); public abstract void Unregisterreceiver (Broadcastreceiver receiver);}
Public abstract class Broadcastreceiver {public abstract void onreceive (context context, Intent Intent);
public class Activity extends Contextthemewrapper ... { //Contextthemewrapper extends Contextwrapper //Contextwrapper extends Context}
Class Mediareceiver extends Broadcastreceiver { //override OnReceive Method}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
The observer pattern for Java design patterns