首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Swing 組件應用觀察者模式:代理模式實現非侵入式監聽

     編輯:程式設計疑難解答

問題

Swing 組件(如 JButton)已封裝完成,無法直接實現自定義 Observer 接口。如何在不修改組件源碼的前提下引入觀察者模式?

解決方案:代理模式

創建代理類包裝目標組件,代理類實現監聽接口,內部持有組件引用,轉發調用並擴展功能:

// 1. 定義觀察者接口
public interface ButtonObserver {
    void onClick(JButton source);
}

// 2. 代理類實現接口,包裝 JButton
public class JButtonProxy implements ButtonObserver {
    private JButton target;
    private List observers = new ArrayList<>();

    public JButtonProxy(JButton button) {
        this.target = button;
        // 給原組件添加匿名監聽,觸發時通知所有觀察者
        target.addActionListener(e -> notifyObservers());
    }

    public void addObserver(ButtonObserver obs) { observers.add(obs); }

    private void notifyObservers() {
        for (ButtonObserver obs : observers) obs.onClick(target);
    }

    // 代理 JButton 的其他方法...
    public void setText(String text) { target.setText(text); }
    // ...
}

優勢

  • 不修改原組件代碼,符合開閉原則。
  • 可動態添加/移除觀察者,解耦業務邏輯與 UI 組件。
  • 適用於任何無法修改的第三方類。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved