Java Watcher Mode (Observer mode)

Source: Internet
Author: User

Java to a certain extent, it is inevitable to encounter the concept of design pattern, understanding design patterns, will make their own Java interface or abstract class application have a deeper understanding. Design Patterns in the Java medium-sized system applications, follow a certain programming mode, to make their own code easy to understand, easy to communicate, OBSERVER (Observer) mode is a more commonly used mode, especially in the interface design, the application of a broad, and this tutorial is concerned about Java in e-commerce system Application , so I want to analyze the application of observer from the example of e-commerce.

Although online stores in various forms, each site has its own characteristics, but also has its general commonality, single on the "Change in order to notify subscribers in a timely manner," This is a lot of online shop common mode, this model is similar to observer patern.

Specifically, if the product in the online store changes in terms of name price, if the system can automatically notify members, it will be a major feature of the online store to distinguish between traditional shops. This would require the inclusion of the observer role in commodity product, so that when product details change, observer can automatically observe this change and be able to perform timely update or notify actions.


The Java API also provides us with a ready-made Observer interface Java.util.Observer. We just need to use it directly.

We must extends Java.util.Observer to really use it:

    • Methods of providing add/delete observer;
    • Provides a way to notify (NOTISFY) all observer.
1//Product class is available for JSP to use Usebean directly invoke the class main execution product database Insert Update 2 public class product extends observable{3 private String name; 4 privat e float price; 5 public String GetName () {return name,} 6 public void SetName () {7        this.name=name; 8        //Set Change point 9        s Etchanged ();        notifyobservers (name), one}, public float GetPrice () {return price;} public void Setprice () {        this.price=price;15        //Set Change point        setchanged ();        notifyobservers (n EW Float (Price)); 18}19//The following can be a database update insert command. public void Savetodb () {.........         }23}

We note that in the Setxxx method in the product class, we set the Notify (notification) method, and when the JSP table is setxxx, the Notisfyobservers method is actually triggered, which informs the corresponding observer that action should be taken.

Let's look at the code of these observers and what they are doing:

1//Observer Nameobserver is mainly used to observe the product name (name) 2 public class Nameobserver implements observer{3 private String name=null; 4 public void update (Observable obj,object arg) {5 if (arg instanceof String) {6 name= (string) arg; 7//Product name change Value in Name 8 System.out.println ("Nameobserver:name changet to" +name); 9}10}11}12 13//viewer priceobserver mainly used to observe the price of the product, the public class Priceobserver implements OBSERVER{15 Priva Te float price=0;16 public void update (Observable obj,object arg) {if (arg instanceof float) {price= (float ARG). Floatvalue (); System.out.println ("Priceobserver:p rice Changet to" +price); 20}21}22}

In JSP we can formally execute this observer program:

 1 <jsp:usebean id= "Product" scope= "session" class= "Product"/> 2 <jsp:setproperty name= "Product" property = "*"/> 3 4 <jsp:usebean id= "Nameobs" scope= "session" class= "Nameobserver"/> 5 <jsp:setproperty name= "Produc  T "property=" * "/> 6 7 <jsp:usebean id=" Priceobs "scope=" session "class=" Priceobserver "/> 8 <jsp:setproperty Name= "Product" property= "*"/> 9 <%11 if (Request.getparameter ("Save")!=null) {product.savetodb (); OU T.PRINTLN ("Product Data changes Save! and has been automatically notified to the customer ");}else{16//JOIN the Observer Product.addobserver (nameobs); Product.addobserver (priceobs);%>20//reque   St.getrequesturi () is the name of the program that produces this JSP, which calls itself <form action= "<%=request.getrequesturi ()%>" method=post>22  <input Type=hidden name= "Save" value= "1" >23 Product Name: <input type=text name= "name" >24 product Price: <input type=text Name= "Price" >25 <input type=submit>26 </form>27 <%28}29%> 

To execute the JSP program, a form entry interface will appear, which requires entering the product name product price, clicking Submit, or executing the code between the IF (Request.getparameter ("Save")!=null) of the JSP.


Since the concept of automatic assignment of data JavaBeans is used here, the actual program automatically executes the SetName setprice statement. You will find the following information in the server console:
1     nameobserver:name changet to????? (The name of the product entered in the JSP form) 2     priceobserver:p changet to??? (The price of the product entered in the JSP form);

This means the observer is already in action.


You will also get information on the browser that executes the JSP:
Product data changes to save! and has automatically notified customers

As a result of the use of JSP concept, there are a lot of automatic actions, now call the Observer's Java code is written as follows:
1 public class Test {2 public static void Main (String args[]) {3 Product product=new product (); 4 nameobserver Nameobs=new Nameobserver (); 5 priceobserver priceobs=new priceobserver (); 6  7//Join Observer 8 Product.addobserver (Nameobs), 9 product.addobserver (priceobs), Product.setname ("Orange red "); Product.setprice (9.22f); 13}14}

You will find the following information:

Nameobserver:name Changet to Orange red.
Priceobserver:p Changet to 9.22

This means the observer is acting.

Java Watcher Mode (Observer mode)

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.