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 //the Product class is available for JSP to use Usebean directly to invoke the main execution product database insert Update2  Public classProduct extends observable{3     PrivateString name;4     Private floatPrice ;5      PublicString GetName () {returnname;}6      Public voidSetName () {7              This. name=name;8             //Set Change Point9 setchanged ();Ten notifyobservers (name); One } A      Public floatGetPrice () {returnPrice ;} -      Public voidSetprice () { -              This. price=Price ; the             //Set Change Point - setchanged (); -Notifyobservers (NewFloat (price)); - } +     //The following can be the database update Insert command. -      Public voidSavetodb () { + ... ........... A         } at}

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 //The observer Nameobserver is primarily used to observe the product name2  Public classNameobserverImplementsobserver{3     PrivateString name=NULL;4      Public voidUpdate (Observable obj,object arg) {5       if(ARGinstanceofString) {6Name=(String) arg;7        //Product Name change value in name8System.out.println ("Nameobserver:name changet to" +name);9 }Ten } One } A  - //The observer Priceobserver is mainly used to observe the price of the product -  Public classPriceobserverImplementsobserver{ the     Private floatPrice=0; -      Public voidUpdate (Observable obj,object arg) { -       if(ARGinstanceofFloat) { -Price=((Float) arg). Floatvalue (); +System.out.println ("Priceobserver:p rice changet to" +Price ); - } + } A}

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= "Product" property= "*"/>6 7<jsp:usebean id= "Priceobs" scope= "Session"class= "Priceobserver"/>8<jsp:setproperty name= "Product" property= "*"/>9 Ten<% One if(Request.getparameter ("save")! =NULL) A { - Product.savetodb (); -OUT.PRINTLN ("Product Data changes Save! and has automatically notified the customer "); the}Else{ -     //JOIN the Observer - Product.addobserver (nameobs); - Product.addobserver (priceobs); +%> -     //Request.getrequesturi () is the name of the program that produces this JSP, which calls itself +<form action= "<%=request.getrequesturi ()%>" method=post> A<input Type=hidden name= "Save" value= "1" > atProduct Name: <input type=text name= "Name" > -Product Price: <input type=text name= "Prices" > -<input type=submit> -</form> -<% - } in%>

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 product name 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 classTest {2      Public Static voidMain (String args[]) {3Product product=NewProduct ();4Nameobserver nameobs=Newnameobserver ();5Priceobserver priceobs=Newpriceobserver ();6 7       //JOIN the Observer8 Product.addobserver (nameobs);9 Product.addobserver (priceobs);Ten  OneProduct.setname ("Orange red."); AProduct.setprice (9.22f); - } -}

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.