Table 33.1: Subject-Observer Classes public interface Observable { public void notifyObservers(); public void register(Observer obs); public void unRegister(Observer obs); }
ReportManager类(Listing33.1)提供了声明在Observable接口中方法的实现。两个依靠于ReportManager的报表对象使用这些方法注册它们自己为观察者。ReportManager把这些注册的观察者保存到observersList矢量(vector)中。当前选择的分类构成了ReportManager对象的状态,它以实例变量的形式保存在变量department中。当为department设置一个新的值时(也就是ReportManager对象的状态改变),notifyObservers方法被调用。作为notifyObservers方法的一部分,ReportManager调用注册为观察者的refreshData(Observable)方法。 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
//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
类之间的关联描述如下:
Figure 33.3: Example application--Class Association