Initial learning of the observer pattern--self-fulfilling

Source: Internet
Author: User

Observer pattern: First of all, to understand the definition of the observer pattern, a one-to-many relationship between objects, when one of the object changes [subject], other objects dependent on the object [Observer], will be notified, and automatically update their own state.

The target object is the source: subject, which should contain an add () \ Remove () \ Notify () Basic single method, respectively, for registering the Observer, deleting the observer, and notifying the observer.

The Observer object: Observer should have the update () method, which automatically executes the Update method and updates its status information when it receives the change notification of the dependent object.

The code implements the Observer pattern---> basic steps are as follows:

1, (subject) the establishment of a target object (interface), which provides for uniform method rules.

2, the establishment of the target class, all must realize the subject interface.

3, the definition of the Observer interface, the Observer interface, contains the Update method.

4, the establishment of the specific observer, the realization of the Observer interface.

The specific code is as follows:

The establishment of the subject interface:

 Public InterfaceSubject {/*** function Description: <br> *〈 function Detailed description register as an observer *@paramObserver *@see[Related Classes/methods] (optional) *@since[Product/module version] (optional)*/    voidregisterobserver (Observer Observer); /*** function Description: <br> *〈 function description "Cancel to be an observer * *@paramObserver *@see[Related Classes/methods] (optional) *@since[Product/module version] (optional)*/    voidremoveobserver (Observer Observer); /*** function Description: <br> *〈 function Detail Description] Notify all observers * *@see[Related Classes/methods] (optional) *@since[Product/module version] (optional)*/    voidnotifyobservers ();}

The specific target class is built: The code that contains the handy test that you write.

 Public classGoodsdataImplementsSubject {PrivateArraylist<observer>observers; PrivateString name; Private intnum; Private intPrice ;  PublicGoodsdata () {observers=NewArraylist<observer>(); } @Override Public voidregisterobserver (Observer Observer) {observers.add (Observer); } @Override Public voidremoveobserver (Observer Observer) {inti =OBSERVERS.INDEXOF (Observer); if(I >= 0) {observers.remove (i); }} @Override Public voidnotifyobservers () { for(Observer o:observers) {o.update (name, num, price); }    }    /*** function Description: <br> *〈 Function Detailed description of changes in the product parameters to notify the Observer changes * *@see[Related Classes/methods] (optional) *@since[Product/module version] (optional)*/     Public voidgoodschanged () {notifyobservers (); }    /*** function Description: <br> *〈 function Detailed description of real-time access to product parameters, test method * *@paramname *@paramnum *@paramPrice *@see[Related Classes/methods] (optional) *@since[Product/module version] (optional)*/     Public voidSetgoodsdata (String name,intNumintPrice ) {         This. Name =name;  This. num =num;  This. Price =Price ;    Goodschanged (); }}

Definition of the Observer's interface: the main definition of a unified Update method

 Public InterfaceObserver {/*** function Description: <br> *〈 function Detailed description The latest data of the viewer and the new topic *@paramname *@paramNum Number *@paramPrice *@see[Related Classes/methods] (optional) *@since[Product/module version] (optional)*/    voidUpdate (String name,intNumintPrice );}

Define the class definition of the specific observer: Of course, there are some additional operational codes that are handy for testing.

 Public classSuguomarketImplementsObserver, displayelement {PrivateString name; Private intnum; Private intPrice ; PrivateSubject Goodsmarket;  PublicSuguomarket (Subject goodsmarket) { This. Goodsmarket =Goodsmarket; Goodsmarket.registerobserver ( This); }    /*** function Description: <br> *〈 function description) Cancellation NOTE * *@see[Related Classes/methods] (optional) *@since[Product/module version] (optional)*/     Public voidRemoveobserver () {Goodsmarket.removeobserver ( This); } @Override Public voiddisplay () {System.out.println ("Name:" + name + "Quantity:" + num + "Price:" +Price ); } @Override Public voidUpdate (String name,intNumintPrice ) {         This. Name = "Su Guo" +name;  This. num =num;  This. Price =Price ;    Display (); }}

Finally, simply write a test class code, easy to run the query real-time effect:

 Public classMarkerttest { Public Static voidMain (string[] args) {Goodsdata goods=NewGoodsdata (); Suguomarket Suguo=Newsuguomarket (goods); Goods.setgoodsdata ("Cigarettes", 20, 100); Goods.setgoodsdata ("Beer", 100, 5); Goods.setgoodsdata ("Bliss", 100, 2); //Cancel RegistrationSuguo.removeobserver (); Goods.setgoodsdata ("Chewing gum", 100, 2); }}

At this end, a simple observer pattern is established, followed by Java's JDK-owned API to implement the Observer pattern

Initial learning of the observer pattern--self-fulfilling

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.