Szukaj…


Prosty przykład MVP

Aby zilustrować prosty przykład użycia wzorca MVP, rozważ następujący kod, który tworzy prosty interfejs użytkownika z tylko przyciskiem i etykietą. Po kliknięciu przycisku etykieta jest aktualizowana liczbą kliknięć przycisku.

Mamy 5 klas:

  • Model - POJO do utrzymania stanu (M w MVP)
  • Widok - klasa z kodem interfejsu użytkownika (V w MVP)
  • ViewListener - interfejs zapewniający metody reagowania na akcje w widoku
  • Prezenter - odpowiada na dane wejściowe i aktualizuje widok (P w MVP)
  • Aplikacja - „główna” klasa, która łączy wszystko razem i uruchamia aplikację

Minimalna klasa „modelowa”, która utrzymuje tylko jedną zmienną count .

/**
 * A minimal class to maintain some state 
 */
public class Model {
    private int count = 0;

    public void addOneToCount() {
        count++;
    }

    public int getCount() {
        return count;
    }
}

Minimalny interfejs powiadamiający słuchaczy:

/**
 * Provides methods to notify on user interaction
 */
public interface ViewListener {
    public void onButtonClicked();
}

Klasa widoku konstruuje wszystkie elementy interfejsu użytkownika. Widok i tylko widok powinien mieć odniesienie do elementów interfejsu użytkownika (tj. Bez przycisków, pól tekstowych itp. W prezenterie lub innych klasach).

/**
 * Provides the UI elements
 */

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.WindowConstants;

public class View {
    // A list of listeners subscribed to this view
    private final ArrayList<ViewListener> listeners;
    private final JLabel label;
    
    public View() {
        final JFrame frame = new JFrame();
        frame.setSize(200, 100);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setLayout(new GridLayout());

        final JButton button = new JButton("Hello, world!");

        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(final ActionEvent e) {
                notifyListenersOnButtonClicked();
            }
        });
        frame.add(button);

        label = new JLabel();
        frame.add(label);

        this.listeners = new ArrayList<ViewListener>();

        frame.setVisible(true);
    }

    // Iterate through the list, notifying each listner individualy 
    private void notifyListenersOnButtonClicked() {
        for (final ViewListener listener : listeners) {
            listener.onButtonClicked();
        }
    }

    // Subscribe a listener
    public void addListener(final ViewListener listener) {
        listeners.add(listener);
    }

    public void setLabelText(final String text) {
        label.setText(text);
    }
}

Logikę powiadomień można również zakodować w Java8 w następujący sposób:

        ...
        final Button button = new Button("Hello, world!");
        // In order to do so, our interface must be changed to accept the event parametre
        button.addActionListener((event) -> {
            notifyListeners(ViewListener::onButtonClicked, event);
            // Example of calling methodThatTakesALong, would be the same as callying:
            // notifyListeners((listener, long)->listener.methodThatTakesALong(long), 10L)
            notifyListeners(ViewListener::methodThatTakesALong, 10L);
        });
        frame.add(button);
        ...

/**
 * Iterates through the subscribed listeneres notifying each listener individually.
 * Note: the {@literal '<T>' in private <T> void} is a Bounded Type Parametre. 
 *
 * @param <T>      Any Reference Type (basically a class).
 * 
 * @param consumer A method with two parameters and no return, 
 *                 the 1st parametre is a ViewListner, 
 *                 the 2nd parametre is value of type T.
 * 
 * @param data     The value used as parametre for the second argument of the
 *                 method described by the parametre consumer.
 */
private <T> void notifyListeners(final BiConsumer<ViewListener, T> consumer, final T data) {
    // Iterate through the list, notifying each listener, java8 style 
    listeners.forEach((listener) -> {

        // Calls the funcion described by the object consumer.
        consumer.accept(listener, data);

        // When this method is called using ViewListener::onButtonClicked
        // the line: consumer.accept(listener,data); can be read as:
        // void accept(ViewListener listener, ActionEvent data) {
        //     listener.onButtonClicked(data);
        // }
        
    });
}

Interfejs musi zostać refaktoryzowany, aby przyjąć ActionEvent jako parametr:

public interface ViewListener {
    public void onButtonClicked(ActionEvent evt);
    // Example of methodThatTakesALong signature
    public void methodThatTakesALong(long );
}

Tutaj potrzebna jest tylko jedna metoda notyfikacji, faktyczna metoda detektora i jego parametr są przekazywane jako parametry. W razie potrzeby można go również użyć do czegoś nieco mniej sprytnego niż faktyczna obsługa zdarzeń, wszystko działa, dopóki w interfejsie znajduje się metoda, np .:

        notifyListeners(ViewListener::methodThatTakesALong, -1L);

Prezenter może przyjąć widok i dodać się jako słuchacz. Po kliknięciu przycisku w widoku widok informuje wszystkich słuchaczy (w tym prezentera). Teraz, gdy prezenter zostanie powiadomiony, może podjąć odpowiednie działania, aby zaktualizować model (tj. Stan aplikacji), a następnie odpowiednio zaktualizować widok.

/**
 * Responsible to responding to user interaction and updating the view
 */
public class Presenter implements ViewListener {
    private final View view;
    private final Model model;

    public Presenter(final View view, final Model model) {
        this.view = view;
        view.addListener(this);
        this.model = model;
    }

    @Override
    public void onButtonClicked() {
        // Update the model (ie. the state of the application)
        model.addOneToCount();
        // Update the view
        view.setLabelText(String.valueOf(model.getCount()));
    }
}

Aby złożyć wszystko w całość, widok można utworzyć i wprowadzić do prezentera. Podobnie można utworzyć i wstrzyknąć model początkowy. Chociaż oba można utworzyć w prezencie, wstrzyknięcie ich do konstruktora pozwala na znacznie prostsze testowanie.

public class Application {
    public Application() {
        final View view = new View();
        final Model model = new Model();
        new Presenter(view, model);
    }

    public static void main(String... args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Application();
            }
        });
    }
}


Modified text is an extract of the original Stack Overflow Documentation
Licencjonowany na podstawie CC BY-SA 3.0
Nie związany z Stack Overflow