Usage scenarios for observer patterns in Java

Source: Internet
Author: User

The Observer pattern is a very classic and very common design pattern.

The behavior of one object depends on the state of another object. Or in other words, when the state of the object being observed changes, it directly affects the behavior of the observed object.

Feature one: The Observer and the observer are generally a one-to-many relationship, an observer corresponds to multiple observers, and when the state of an observer is changed, the Observer notifies the observer, and then the business logic can be processed within the viewer.


The JDK provides a set of observer pattern implementations, in the Java.util package, the Java.util.Observable class, and the Java.util.Observer interface. Observable is the observer, and Observer is the observer.


Below is an introduction to the properties and methods of the observed person

Class Observable {obs:vector//Viewer list Addobserver (Observer O)//Add observer Deleteobserver (Observer O)//delete observer Notifyobservers ( //Notify Observer, callback Observer's update () method Notifyobservers (Object Arg)}

Below is the observer's introduction, the observer will implement observer excuses, rewrite the Update method, and then inject the observer into the Observer

Interface Observer {public void update (Event evt);

The following is a specific application scenario that is thought of.


Involves 3 classes, order class, event class, work order class,

The Order class contains the Id,state attribute, State 1 is on, and 0 is off.

The event class includes the Id,allowclose property, and the allowclase represents whether it can be closed.


When the order status is changed and closed, the orders and events associated with the order can be closed, otherwise the corresponding ticket and event will not be closed if the order status is turned on.

This article is from the "Java Stuff" blog, so be sure to keep this source http://1027187712.blog.51cto.com/5509347/1743743

Usage scenarios for observer patterns in Java

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.