Observer Observer mode __java of Java design pattern

Source: Internet
Author: User
Tags types of themes

There is a Japanese bank project, today I have to do the framework support, a lot of do not understand, so the preliminary study. The feeling is as follows.

Java depth to a certain extent, it is inevitable to encounter the concept of design patterns, understanding design patterns, will make their Java interface or abstract class applications have a deeper understanding. Design patterns are widely used in Java midsize systems, followed by certain programming patterns, In order to make their code easy to understand, easy to communicate, OBSERVER (Observer) mode is a more commonly used mode, especially in the interface design widely used.

Examples add later, busy!!!!!!!!!

Here it comes

Observer mode (Observer pattern) is useful when designing a consistent (synchronized) Exchange model between a set of dependent objects and the objects on which they depend. It keeps the state of dependent objects synchronized with the state of the objects on which they depend. This group of dependent objects refers to the Observer (Observer), and the objects they depend on are called themes (Subject). In order to realize the state of the Observer (Observer) in sync with the subject (SUBJECT), the Observer mode (Observer pattern)
  
The Publisher-Subscriber (Publisher--subscriber) model is recommended to make clear boundaries between this group of Observers (Observer) and subject (Subject) objects.
  
A typical observer (Observer) is an object that relies on or focuses on the state of the subject object. A theme can have one or more observers. These observers need to be notified when the status of the subject changes.
  
A topic cannot maintain a static observer list because the Observer list for the given principal needs to change dynamically. So any object that focuses on the state of the subject needs to explicitly register itself as an observer of the subject. The change in the subject state will require all the registered observers to be notified. After the topic is notified, each observer queries the subject to synchronize its status with the subject. So a theme plays the role of the publisher, releasing information to all subscribed observers.
  
In other words, the subject and its observer contain a one-to-many relationship. When the state of an instance of a theme changes, all observers who depend on it are notified and updated. Each observer object needs to be registered with the subject and notified when the status of the subject changes. An observer can register or subscribe to multiple topics. When the observer does not want to be notified again, it can log off the subject.
  
   in order to achieve this mechanism:
  
(1) The theme needs to provide an interface for registration and logoff notifications.
  
(2) The following two points also need to meet:
  
A, pull model (in the pull)--the theme needs to provide an interface that allows the observer to query the subject to get the necessary status information to update its status.
  
B, push model (in the push mode)--the topic sends the state information that the observer may be concerned about.
  
(3) The observer needs to provide an interface that can receive notification from the subject.
  
The class diagram (Figure 33.1) describes a structure that is not homogeneous and an association between them to satisfy the above requirements.
    
Figure 33.1:generic Class Association when the Observer pattern is applied
  


From this class diagram you can see:
  
(1) All themes need to provide an implementation similar to the observable interface.
  
(2) All observers need to provide an implementation similar to the Observer interface.
  
There are several variants when applying the observer pattern. This produces different types of themes--observer patterns, for example, where the observer focuses only on specific types of changes in the subject.
  
Add New Viewer:
  
After applying the observer pattern, you can dynamically add different observers without affecting the subject class. Similarly, when the state of the subject changes logically, the observer will not be affected.
  
Example:
  
In order to manage a variety of products sold in the factory, let us establish a sales report system. This system has the following characteristics:
  
(1) Users can choose a category they are interested in
  
(2) After you select a category, you need to display the following two types of reports.
  
A, monthly Statement (monthly Report)-------All transactions list for the month of the selected category.
  
B, Annual cumulative Amount (YTD Sales chart)-Displays the annual cumulative amount of the selected category in months.
  
(3) When a different category is selected, the data for both reports is refreshed, displaying the report for the currently selected category.
  
To achieve the desired functionality, it is easy to see that two report objects rely on objects that hold user-selected classifications. Applying observer mode to this scenario, we can design a consistent (synchronized) Exchange model between objects that hold user-selected categories and two Report objects.
  
Let's define three classes, which function as described in table 33.1:
  
Table 33.1:subject-observer Classes
Public interface Observable {
public void notifyobservers ();
public void Register (Observer obs);
public void Unregister (Observer obs);
}
  
The Reportmanager Class (Listing33.1) provides an implementation of the method declared in the observable interface. Two Reportmanager-dependent report objects use these methods to register themselves as observers. Reportmanager saves these registered observers to the observerslist vector (vectors). The currently selected taxonomy forms the state of the Reportmanager object, which is stored in the variable department as an instance variable. The Notifyobservers method is invoked when a new value is set for department (that is, when the state of the Reportmanager object changes). As part of the Notifyobservers method, Reportmanager invokes the RefreshData (observable) method registered as an observer.
Listing 33.1:reportmanager Class
  
public class Reportmanager extends JFrame
Implements observable {
...
...
Private Vector observerslist;
Private String Department;
Public Reportmanager () throws Exception {
...
...
Observerslist = new Vector ();
...
...
}
public void Register (Observer obs) {
Add to the list of observers
Observerslist.addelement (OBS);
}
public void Unregister (Observer obs) {
Remove from the list of observers
}
public void Notifyobservers () {
Send notify to all observers
for (int i = 0; i < observerslist.size (); i++) {
Observer Observer =
(Observer) Observerslist.elementat (i);
Observer.refreshdata (this);
}
}
Public String getdepartment () {
Return department;
}
public void Setdepartment (String dept) {
Department = Dept;
}
Class Buttonhandler implements ActionListener {
Reportmanager subject;
public void actionperformed (ActionEvent e) {
if (E.getactioncommand (). Equals (Reportmanager.exit)) {
System.exit (1);
}
if (E.getactioncommand (). Equals (REPORTMANAGER.SET_OK)) {
String dept = (String)
Cmbdepartmentlist.getselecteditem ();
Change in state
Subject.setdepartment (dept);
Subject.notifyobservers ();
}
}
Public Buttonhandler () {
}
Public Buttonhandler (Reportmanager manager) {
Subject = Manager;
}
}
}//end of Class
  
In addition to providing an implementation of the observable interface method, Reportmanager also shows the necessary user interface to allow the user to select a specific, focused category.
  
Let's define two implementations of the interface Observer: Monthlyreport and Ytdchart classes
  
Public interface Observer {
public void RefreshData (observable subject);
}
    
Figure 33.2:observer Class Hierarchy
  


Listing 33.2:monthlyreport Class as an Observer
  
public class Monthlyreport extends JFrame implements Observer {
...
...
Private Reportmanager Objreportmanager;
Public Monthlyreport (Reportmanager Inp_objreportmanager)
Throws Exception {
Super ("Observer pattern--Example");
Objreportmanager = Inp_objreportmanager;
Create controls
...
...
Create Labels
...
...
Objreportmanager.register (this);
}
public void RefreshData (observable subject) {
if (subject = = Objreportmanager) {
Get subject ' s state
String Department = objreportmanager.getdepartment ();
Lbltransactions.settext (
"Current Month transactions-" +
department);
Vector trnlist =
Getcurrentmonthtransactions (department);
String content = "";
for (int i = 0; i < trnlist.size (); i++) {
Content = content +
Trnlist.elementat (i). toString () + "n";
}
Tatransactions.settext (content);
}
}
Private Vector getcurrentmonthtransactions (String Department
) {
Vector v = new vector ();
Fileutil futil = new Fileutil ();
Vector allrows = Futil.filetovector ("Transactions.date");
Current month
Calendar cal = Calendar.getinstance ();
Cal.settime (New Date ());
int month = Cal.get (calendar.month) + 1;
String SEARCHSTR = department + "," + month + ",";
int j = 1;
for (int i = 0; i < allrows.size (); i++) {
String str = (string) allrows.elementat (i);
if (Str.indexof (SEARCHSTR) > 1) {
StringTokenizer st =
New StringTokenizer (str, ",");
St.nexttoken ();//bypass the Department
str = "" + j + "." + st.nexttoken () + "/" +
St.nexttoken () + "~ ~ ~" +
St.nexttoken () + "Items" + "~ ~ ~" +
St.nexttoken () + "dollars";
j + +;
V.addelement (str);
}
}
return v;
}
}//end of Class
  
Reportmanager uses this interface to notify all its observers.
  
   subject-Observer's Association (Subject--observer Association)
  
Typically, a customer first needs to create a theme (Reportmanager) instance, when an observer (for example: Monthlyreport,ytdchart) object is created. The customer passes a reference to the subject Reportmanager instance to the observer's constructor, and the observer registers itself with the current subject instance.
  
Client Code
public class Supervisorview {
...
...
public static void Main (string[] args) throws Exception {
Create the Subject
Reportmanager objsubject = new Reportmanager ();
Create observers
New Monthlyreport (Objsubject);
New Ytdchart (Objsubject);
}
}//end of Class
  
The association between classes is described as follows:
    
Figure 33.3:example Application--class Association
  


Logical process:
  
(1) using the Reportmanager user interface, when the user selects a specific category and clicks the OK button, the Reportmanager's internal state is changed (for example, reportmanager instance variable department value changes).
  
(2) Once the new state is set, the Reportmanager invokes the RefreshData (observable) method of two registered observers Monthlyreport and Ytdchart.
  
(3) As part of the RefreshData method, two of the respondents need to:
  
A, check to make sure that the subject of the call RefreshData method and the viewer of this book are subject to the same theme. This avoids the observer responding to unnecessary calls.
  
B, use the Getdepartment method to query the current state of the Reportmanager.
  
C, the data displayed from the data file to extract the response.
    
Figure 33.4:monthlyreport View



Any observer is unaffected when the Reportmanager state change logic implementation needs to change. Similarly, when a new observer is added, the Reportmanager class does not need any change.

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.