MVC上特定字段的观察者模式

时间:2019-04-19 21:42:05

标签: java model-view-controller listener observer-pattern

在MVC模式上,这是Model通知View的最佳选择(如果这首先是正确的方法),那么从Model存储的所有数据字段中,只有其中几个已更新。特别是当我们只想更新视图的特定字段时。

我目前正在使用带有观察者/订阅者(JAVA Swing)的MVC模式,如下所述:https://stackoverflow.com/a/6963529,但是当模型更新时,它会在调用update()函数时更改视图中的所有内容,无法确定要更改模型中的哪个字段以便仅更新视图中的必填字段。

我阅读了这个主题:https://softwareengineering.stackexchange.com/a/359008和这个主题:https://stackoverflow.com/a/9815189,我认为这很有用,但是对于后来的我,我不太了解如何在variale上设置propertyChangeListener。 (int,float等)。也与此相关:https://stackoverflow.com/a/9815189

开始运行软件的Main类:

public class Main {
    public static void main(String[] args) {
        Model m = new Model();
        View v = new View(m);
        Controller c = new Controller(m, v);
        c.initController();
    }
}

所以我在Model上的代码是这样的:

public class Model extends Observable {
   //...
   private float speed;
   private int batteryPercentage;

   public float getSpeed() {
       return speed;
   }
   public void setSpeed(float speed) {
       this.speed = speed;
       setChanged();
       notifyObservers();
   }

    public int getBatteryPercentage() {
        return batteryPercentage;
    }
    public void setBatteryPercentage(int batteryPercentage) {
        this.batteryPercentage = batteryPercentage;
        setChanged();
        notifyObservers();
    }
}

视图知道模型:

public class View implements Observer {
    private Model model;
    private JTextField txtFldSpeed;
    private JTextField txtFldBattery;
    private JFrame mainWindow;

    public View(Model m) {
        this.model = m;
        initialize();
    }
    private void initialize() {
        mainWindow = new JFrame();
        mainWindow.setTitle("New Window");
        mainWindow.setMinimumSize(new Dimension(1280, 720));
        mainWindow.setBounds(100, 100, 1280, 720);
        mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel tPanel1 = new JPanel();
        tPanel1.setBorder(new LineBorder(new Color(0, 0, 0)));
        tPanel1.setLayout(null);
        mainWindow.getContentPane().add(tPanel1);

        mainWindow.getContentPane().add(tPanel1);
        txtFldSpeed = new JTextField();
        txtFldSpeed.setEditable(false);
        txtFldSpeed.setBounds(182, 11, 116, 22);
        tPanel1.add(txtFldSpeed);

        txtFldBattery = new JTextField();
        txtFldBattery.setEditable(false);
        txtFldBattery.setBounds(182, 43, 116, 22);
        tPanel1.add(txtFldBattery);

        mainWindow.setVisible(true);
    }
    @Override
    public void update(Observable o, Object arg) {
        txtFldSpeed.setText(Float.toString(model.getSpeed()) + " kn");
        txtFldBattery.setText(Integer.toString(model.getBatteryPercentage()) + " %");
    }
}

控制器将视图添加为模型的观察者:

public class Controller {
    private Model model;
    private View view;

    public Controller(Model m, View v) {
        this.model = m;
        this.view = v;
    }

    public void initController() {    
        model.addObserver(view);
        model.setSpeed(10);
    }
}

我期望的是,在更新模型时,假设调用了函数setSpeed(),该视图被告知需要在特定字段而不是每个“可更改”字段上进行更新。 (如txtFldBattery

我想这样做是因为在View上,每秒更新一次字段两次,并且因为我需要更新View上的所有内容,因此JComboBox不需要更新通常,在尝试选择一个选项时会保持关闭状态。

2 个答案:

答案 0 :(得分:2)

我将使用SwingPropertyChangeSupport,将模型的每个状态字段都设置为“绑定属性”,以便可以分别侦听每个状态字段。

例如,假设您有一个看起来像这样的模型:

public class MvcModel {
    public static final String SPEED = "speed";
    public static final String BATTERY = "battery";
    public static final int MAX_SPEED = 40;
    private float speed;
    private int batteryPercentage;
    private SwingPropertyChangeSupport pcSupport = new SwingPropertyChangeSupport(this);

    public float getSpeed() {
        return speed;
    }

    public void setSpeed(float speed) {
        float oldValue = this.speed;
        float newValue = speed;
        this.speed = speed;
        pcSupport.firePropertyChange(SPEED, oldValue, newValue);
    }

    public int getBatteryPercentage() {
        return batteryPercentage;
    }

    public void setBatteryPercentage(int batteryPercentage) {
        int oldValue = this.batteryPercentage;
        int newValue = batteryPercentage;
        this.batteryPercentage = batteryPercentage;
        pcSupport.firePropertyChange(BATTERY, oldValue, newValue);
    }

    public void addPropertyChangeListener(PropertyChangeListener listener) {
        pcSupport.addPropertyChangeListener(listener);
    }

    public void removePropertyChangeListener(PropertyChangeListener listener) {
        pcSupport.removePropertyChangeListener(listener);
    }

    public void addPropertyChangeListener(String name, PropertyChangeListener listener) {
        pcSupport.addPropertyChangeListener(name, listener);
    }

    public void removePropertyChangeListener(String name, PropertyChangeListener listener) {
        pcSupport.removePropertyChangeListener(name, listener);
    }

}

速度和batteryPercent字段都是“绑定字段”,因为对这些字段的任何更改都会触发属性更改支持对象向已向支持对象注册的所有侦听器发出通知消息,如{ {1}}个方法。

通过这种方式,控制器可以在模型上注册其要侦听的任何属性的侦听器,然后将任何更改通知视图。例如:

public void setXxxx(...)

设置可能类似于:

class SpeedListener implements PropertyChangeListener {
    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        float speed = model.getSpeed();
        view.setSpeed(speed);
    }
}

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.GridLayout;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.*;
import javax.swing.event.SwingPropertyChangeSupport;

public class MVC2 {

    private static void createAndShowGui() {
        MvcModel model = new MvcModel();
        MvcView view = new MvcView();
        MvcController controller = new MvcController(model, view);
        controller.init();

        JFrame frame = new JFrame("MVC2");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(view.getMainDisplay());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}

class MvcView {
    private JPanel mainPanel = new JPanel();
    private JSlider speedSlider = new JSlider(0, MvcModel.MAX_SPEED);
    private JSlider batterySlider = new JSlider(0, 100);
    private JProgressBar speedBar = new JProgressBar(0, MvcModel.MAX_SPEED);
    private JProgressBar batteryPercentBar = new JProgressBar(0, 100);

    public MvcView() {
        speedSlider.setMajorTickSpacing(5);
        speedSlider.setMinorTickSpacing(1);
        speedSlider.setPaintTicks(true);
        speedSlider.setPaintLabels(true);
        speedSlider.setPaintTrack(true);

        batterySlider.setMajorTickSpacing(20);
        batterySlider.setMinorTickSpacing(5);
        batterySlider.setPaintTicks(true);
        batterySlider.setPaintLabels(true);
        batterySlider.setPaintTrack(true);

        speedBar.setStringPainted(true);
        batteryPercentBar.setStringPainted(true);

        JPanel inputPanel = new JPanel(new GridLayout(0, 1));
        inputPanel.add(createTitledPanel("Speed", speedSlider));
        inputPanel.add(createTitledPanel("Battery %", batterySlider));

        JPanel displayPanel = new JPanel(new GridLayout(0, 1));
        displayPanel.add(createTitledPanel("Speed", speedBar));
        displayPanel.add(createTitledPanel("Battery %", batteryPercentBar));

        mainPanel.setLayout(new GridLayout(1, 0));
        mainPanel.add(createTitledPanel("Input", inputPanel));
        mainPanel.add(createTitledPanel("Display", displayPanel));
    }

    private JComponent createTitledPanel(String title, JComponent component) {
        JPanel titledPanel = new JPanel(new BorderLayout());
        titledPanel.setBorder(BorderFactory.createTitledBorder(title));
        titledPanel.add(component);
        return titledPanel;
    }


    public JComponent getMainDisplay() {
        return mainPanel;
    }


    public void setSpeed(float speed) {
        speedBar.setValue((int) speed);
    }


    public void setBatteryPercent(int batteryPercent) {
        batteryPercentBar.setValue(batteryPercent);
    }


    public JSlider getSpeedSlider() {
        return speedSlider;
    }

    public JSlider getBatterySlider() {
        return batterySlider;
    }

}

旁注:Observer和Observable在Java的最新版本中已过时,因此应避免使用它们。

答案 1 :(得分:1)

在您的update方法实现中,您可以通过调用第一个参数o来确定哪个Observable已更改,而使用第二个参数arg则可以在您调用notifyObservers(this.speed);时确定哪个值已更改

请注意, notifyObservers 的签名接受Object,而float原语不是Object的子类。