Understanding the observer mode of java Design Patterns

Source: Internet
Author: User

Understanding the observer mode of java Design Patterns
In actual life, we often encounter changes in data of things, such as the temperature recorder in life. When the temperature changes, we observe the curve of the temperature change, temperature logs. For this type of problem, it is very close to the "Observer mode" in the java design mode. It is suitable for the program structure problem where multiple objects track the changes of an object's data. The Observer design pattern involves two roles: the topic (Subject) and The Observer (Observer). The following uses the existing Observer design pattern code in java JDK to demonstrate the usage: 1. subject: a subclass derived from the Observable class. You only need to define the monitored data and the getter () and setter () methods, the getter method is used to pull data from a specific observer. The setter method is used to update, set the changed variable, and notify the specific observer to respond to the data. The Code is as follows: import java. util. observable; public class Subject extends Observable {private String data; public String getData () {return data;} public void setData (String data) {// update data this. data = data; // set the updated data flag setChanged (); // notify specific observers. Here, the data push function is policyobservers (null);} 2. observer (Observer): compile a specific Observer class to implement the Observer interface, and pass the topic object through parameters to obtain updated data. The update () method is mainly used to pull data and process data. The Code is as follows: import java. util. observable; import java. util. observer; public class ObserverOne implements Observer {@ Override public void update (Observable o, Object arg) {// TODO Auto-generated method stub Subject subject = (Subject) o; System. out. println ("data is being updated to:" + subject. getData () ;}}write a simple test class to test: import java. util. observer; public class Test {public static void main (String [] args) {// TODO Auto -Generated method stub Observer obj = new ObserverOne (); Subject subject = new Subject (); subject. addObserver (obj); subject. setData ("One") ;}} output: "data is being updated to: One". The observer Mode Implemented by java JDK shows that the code is very simple when used, in fact, you can see the source code of the Observerable class and Observer interface. These are all expert-level code. after learning the Observer mode, the following conclusions are drawn: 1) the topic needs to know which observer monitors it, indicating that there must be a collection class member variable in the topic class, adding and deleting and judging whether these observer objects exist. 2) The observer class must be polymorphism and have a common parent class interface. 3) The theme completion function is basically fixed. Adding an observer, revoking the observer, notifying the observer of the message, and causing the observer response (that is, pulling data) can be abstracted. After thinking and summing up above, the following is the observer mode written in a custom form: 1. Write the observer interface (IObserver ). The Code is as follows: public interface IObserver {// The passed parameter object can indirectly obtain the changed topic data public void refresh (ISubject subject);} 2. Compile the topic interface (ISubject ). The Code is as follows: public interface ISubject {// register the observer public void register (IObserver obs); // revoke the observer public void unregister (IObserver obs ); // notify all observers and perform data Response public void policyobservers ();} 3. added the abstract topic class layer (AbstractSubject ). The Code is as follows: import java. util. arrayList; public class AbstractSubject implements ISubject {private ArrayList <IObserver> array = new ArrayList <IObserver> (); @ Override public void register (IObserver obs) {// TODO Auto-generated method stub array. add (obs) ;}@ Override public void unregister (IObserver obs) {// TODO Auto-generated method stub array. remove (obs) ;}@ Override public void policyobservers (){// TODO Auto-generated method stub for (int I = 0; I <array. size (); I ++) {IObserver obs = array. get (I); obs. refresh (this) ;}}} 4. the topic subclass defines the monitored data (Subject ). The Code is as follows: public class Subject extends actsubject {// the monitored data private String data; public String getData () {return data;} public void setData (String data) {this. data = data ;}} 5. the Observer object (Observer) "pulls" data to get the data response. The Code is as follows: public class Observer implements IObserver {@ Override public void refresh (ISubject obj) {// TODO Auto-generated method stub Subject subject = (Subject) obj; System. out. println ("data is being updated to:" + subject. getData () ;}finally write a Test class to Test: public class Test {public static void main (String [] args) {// TODO Auto-generated method stub IObserver obs = new Observer (); Subject subject = new Subject (); subject. Register (obs); subject. setData ("one"); subject. policyobservers () ;}} the output result is the same!

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.