Observer pattern

本文介绍观察者模式的应用场景及实现方式,通过示例展示如何在GUI应用程序中使用此模式,保持对象间的一致性并减少耦合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Definition


One object changes state, all of its dependents are updated automatically.

Where to use & benefits

One change affects one or many objects.
Many object behavior depends on one object state.
Need broadcast communication.
AKA “Publish-Subscribe”.
Maintain consistency between objects
keep classes from becoming too tightly coupled, which would hamper reusability.

Related patterns include

Singleton, which is used to make observable object unique and accessible globally.
Mediator, which is used to encapsulate updated objects.

Example


Observer pattern is often used in GUI application. For example, defining a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically, like stock change affecting many data or diagram updated accordingly.

Java API provides a built-in interface Observer and class Observable for use.

To show how observer pattern works, two windows have been created. One is for user input; another is for display. When the data has been entered in the textfield, another window gets the message and display it with a dialog. The private inner classes have been used in this example.
import javax.swing.*;
import java.awt.event.*;
import java.util.*;

class DisplayForm extends JFrame {
    InputFormObserver input = new InputFormObserver();
    InputForm inputForm ;
    Observable obsInput;
    JTextField display;
    //...
    public DisplayForm() {       
        addWindowListener(new WindowAdapter() {
             public void windowClosing(WindowEvent e) {
                  System.exit(0);
        }});
        inputForm = new InputForm();
        obsInput = inputForm.getInputInfo();
        obsInput.addObserver(input);
   
        display = new JTextField(10);
            display.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                   
               }
           });
        getContentPane().add(display);
        setTitle("Observer form");
        setSize(200,100);
        setLocation(200,100);
        setVisible(true);
    
    }
   
    private class InputFormObserver implements Observer {
         public void update(Observable ob, Object o) {
             doSomeUpdate();
             if (obsInput.countObservers()>0)
                    obsInput.deleteObservers();
             obsInput = inputForm.getInputInfo();
             obsInput.addObserver(input);
         }
        
     }
     public void doSomeUpdate() {
            display.setText(inputForm.getText());
                    JOptionPane.showMessageDialog(DisplayForm.this,
                            "This form has been updated");
    }
    public static void main(String args[]) {
        DisplayForm df = new DisplayForm();
    }
}
class InputForm extends JFrame {
    public InformDisplay inform = new InformDisplay();
    //...
    JTextField input= new JTextField(10);
       
    public InputForm() {
        JPanel panel= new JPanel();
        input.addActionListener(new ActionListener() {
               public void actionPerformed(ActionEvent e) {
                    inform.notifyObservers();
               }
           });
        panel.add(new JLabel("Enter: "));
        panel.add(input);
        addWindowListener(new WindowAdapter() {
                  public void windowClosing(WindowEvent e) {
                      System.exit(0);
        }});
        getContentPane().add(panel);
        setTitle("Observable form");
        setSize(200,100);
        setVisible(true);
    }
    public Observable getInputInfo() {
        return inform;
    }
   
    public String getText() {
        return input.getText();
    }
   
    private class InformDisplay extends Observable {
        public void notifyObservers() {
            setChanged();
            super.notifyObservers();
        }
        public String getChange() {
            return input.getText();
        }
    }
    //...
}
java DisplayForm

Two windows will come up:
one for user input, the other for observing user input.
Enter data in the input window, a dialog box from other window shows up
and the input data has been shown in the other window.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值