我目前正在使用JavaFX处理桌面应用程序(请注意,我没有使用Screen Builder,而是直接在代码中创建视图)。我想实现MVP(模型视图演示者)模式的“被动视图”变体。
因为我找不到任何清晰的示例。.我试图自己创建一个基本设置。
主要课程
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) throws Exception {
Model model = new Model();
View view = new View(stage);
Presenter presenter = new Presenter(model, view);
}
}
模型
public class Model {
private StringProperty labelText;
public Model() {
this.labelText = new SimpleStringProperty();
}
public String getLabelText() {
return labelText.get();
}
public StringProperty labelTextProperty() {
return labelText;
}
public void setLabelText(String labelText) {
this.labelText.set(labelText);
}
}
查看
public class View {
private Button button;
private Label label;
public View(Stage stage) {
label = new Label("This is a test");
label.setLayoutX(50);
label.setLayoutY(50);
button = new Button("Click me");
button.setLayoutX(200);
button.setLayoutY(50);
Pane pane = new Pane();
pane.getChildren().addAll(label, button);
Scene scene = new Scene(pane, 400, 200); //Standard size 1200, 800
stage.setScene(scene);
stage.show();
}
public Button getButton() {
return button;
}
public void setButton(Button button) {
this.button = button;
}
public Label getLabel() {
return label;
}
public void setLabel(Label label) {
this.label = label;
}
}
演示者
public class Presenter implements EventHandler<ActionEvent> {
private Model model;
private View view;
public Presenter(Model model, View view) {
this.model = model;
this.view = view;
//Register action listener for button
this.view.getButton().setOnAction(this);
//Register change listeners of model
this.model.labelTextProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
//Update view
}
});
}
@Override
public void handle(ActionEvent event) {
if (event.getSource() == this.view.getButton()) {
//Update model
}
}
}
我认为在实现被动视图模式时应考虑以下几点:
使用这些信息,我尝试为模型视图呈现器设置构建此基本结构。我是否正确实现了被动视图?
答案 0 :(得分:0)
对我很好。不确定MVP中的被动指的是什么。因此,您的问题的答案是,是的,您似乎做对了。