Design Pattern-Observer Pattern

Source: Internet
Author: User

There have been a lot of online sharing and notes on the design model. I am still writing this article about nothing new. This is mainly to record my recent learning and life, in addition, I hope to use this blog post to restart my blog to fill my life. I haven't written anything for a long time. I have been watching my blog for a long time and looking back at the blank days of my memory, I felt a little scared. after such a long period of time, I did not even leave any trace. My existence was too environmentally friendly. Let's get into the topic.


1. What is the observer mode?

According to the definition of Head First Design Pattern, the observer mode is used to define a one-to-many relationship between objects so that when one of the objects changes, other Objects of interest can be notified and the status is automatically updated.

In Observer mode, one Observer (Subject) is used to Publish a Publish State, and multiple Observer objects (Observer Object) exist ). The observer object registers or subscribes to the observed Subject (Register or Subscribe) to indicate that it is interested in the publish status of the Subject. The Subject object takes the initiative to inform the Observer object (push mode) or notify the Observer object to obtain the information it is interested in (pull mode) based on its state changes ).

In Observer mode, the Subject does not care about the Observer implementation method, but does not care about the addition and exit of the Observer. The Observer object does not care about the Subject implementation method, as long as it implements a specific interface, provide information of interest to you.


2. Application scenarios

The observer mode is also known as the publisher mode. As the name suggests, this mode is mainly used when an object needs to be released externally and there is a many-to-one dependency between objects, allows multiple observer objects to automatically update themselves based on changes in the status of the observed subject.


3. Implementation Method

In the design and implementation of the observer mode, due to the loose coupling between each other, each other no longer cares about the specific implementation of the other party, but only requires the other party to implement specific interfaces. Therefore, the Observer Subject (Subject) must implement the Subject interface, while the Observer object (Observer) must implement the Observer interface. Forgive me for not finding a painting tool, so I borrowed an image from the Internet to express this relationship.

(Observer mode structure, derived from supercrsky)

The Subject interface defines three methods: attatch (register observer with Subject), detach (delete from registered observer table), and yyobservers (notify Observer object ). The Observer interface defines a method for update to receive the update call of a Subject. In the implementation of the Subject class, because the information of the observer needs to be maintained, a List must be defined to save all the reference of the observer object.

The following is a simple example to show you the implementation of the observer mode. In this example, after the observer body perceives a change in its status (message, send messages to all observer objects. In this example, three different observer implementation classes are defined. They display received messages in different ways, which are displayed as is, converted to uppercase and lowercase.

---------------- Subject. java

package cn.ac.ict.chengenbao;public interface Subject {public void registerObserver(Observer obj);public void removeObserver(Observer obj);public void notifyObservers();}

----------------- Observer. java

package cn.ac.ict.chengenbao;public interface Observer {public void update(String message);}

--------------------- SubjectImpl. java

package cn.ac.ict.chengenbao;import java.util.ArrayList;import java.util.List;public class SubjectImpl implements Subject {private List
 
   observerList = null;private String msg = null;public SubjectImpl() {observerList = new ArrayList
  
   ();}public void registerObserver(Observer obj) {// TODO Auto-generated method stubobserverList.add(obj);}public void removeObserver(Observer obj) {// TODO Auto-generated method stubobserverList.remove(obj);}public void notifyObservers() {// TODO Auto-generated method stubfor( Observer o : observerList) {o.update(msg);}if ( observerList.size() == 0 ) {System.out.println("There is no observers in the list.");}}public void changeMessage(String message) {msg = message;this.notifyObservers();}}
  
 

------------------------ OriginOutputer. java

package cn.ac.ict.chengenbao;public class OriginOutputer implements Observer {private Subject subject = null;public OriginOutputer(Subject s) {subject = s;s.registerObserver(this);}public void update(String message) {// TODO Auto-generated method stubthis.display(message);}private void display(String message) {System.out.println(this.getClass().getName() + ":" + message);}public void leave() {this.display("I remove myself from the ObserverList...");subject.removeObserver(this);}}

----------------------- UpperOutputer. java

package cn.ac.ict.chengenbao;public class UpperOutputer implements Observer {private Subject subject = null;public UpperOutputer(Subject s) {subject = s;s.registerObserver(this);}public void update(String message) {// TODO Auto-generated method stubthis.display(message);}private void display(String message) {System.out.println(this.getClass().getName() + ":" + message.toUpperCase());}public void leave() {this.display("I remove myself from the ObserverList...");subject.removeObserver(this);}}

---------------------------- LowerOutputer. java

package cn.ac.ict.chengenbao;public class LowerOutputer implements Observer {private Subject subject = null;public LowerOutputer(Subject s) {subject = s;s.registerObserver(this);}public void update(String message) {// TODO Auto-generated method stubthis.display(message);}private void display(String message) {System.out.println(this.getClass().getName() + ":" + message.toLowerCase());}public void leave() {this.display("I remove myself from the ObserverList...");subject.removeObserver(this);}}

------------------------ Test. java

package cn.ac.ict.chengenbao;public class Test {public static void main(String[] args) {SubjectImpl subject = new SubjectImpl();LowerOutputer lowerOuter = new LowerOutputer(subject);UpperOutputer upperOuter = new UpperOutputer(subject);OriginOutputer originOuter = new OriginOutputer(subject);subject.changeMessage("Message1");originOuter.leave();subject.changeMessage("Message2");lowerOuter.leave();subject.changeMessage("Message3");upperOuter.leave();subject.changeMessage("Message4");}}

Running result:


4. jdk api support for observer Mode

Jdk api provides native support for the observer mode. The java. util package contains the Observer interface and Observable class. developers can implement the Observer interface and inherit the Observable class to implement the Observer mode.

Using the observer mode that comes with JAVA is subject to the following restrictions:

1) java. util. Observable is a class rather than an interface. This prevents the Subject class to be implemented from inheriting other classes, so that some original classes cannot be migrated to the observer mode. At the same time, implementing the Subject mode through inheritance violates our consistent principle of "Program to the interface.

2) the Observable implements access protection for some key methods. For example, the setChanged method can be called only for Classes inherited from the Observable.

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.