我将 Java 与 Swing 一起使用,想知道是否有关于从对话框获取输入的最佳实践。我使用的是 MVC 架构,我不确定是否应该从模型、 View 或 Controller 完成。
最佳答案
I'm using Java with Swing and was wonder if there was a best practice concerning getting input from a dialog. I'm using a MVC architecture and I'm unsure whether it should be done from the model, the view, or the controller.
乍一看,所有 3 个类(模型、 View 和 Controller )似乎都可以处理输入。
但是,如果我们考虑每个类的角色和职责,就不难决定哪个类适合接收输入。
模型:保存您的数据和处理数据的方法
View :用户界面
Controller:模型和 View 之间的协调器
用最简单的例子来阐述这个想法;一个程序,它接收一个数字(使用 JOptionPane)并显示一条关于它是 odd
还是 even
的消息(通过 JOptionPane)。
模型
模型负责保存数据,以及一些处理数据的方法:
class MyModel
{
private String outcome;
public void checkEvenOdd(int number){
if(number % 2 == 0)
outcome = "even";
else
outcome = "odd";
}
public String getOutcome(){
return outcome;
}
}
毕竟,模型只负责保存数据和逻辑,因此它将把获取数据的工作留给其他人。
景观
View 是用户将与之交互的界面。
class MyView
{
public int promptNumber(){
int num = 0;
String s = JOptionPane.showInputDialog("Enter a number to test whether it is even or odd.");
if(s.matches("\\d+")) //if is numeric
num = Integer.parseInt(s);
else
throw new IllegalArgumentException("Numeric input required.");
return num;
}
public void displayResult(String result){
JOptionPane.showMessageDialog(null, result, "Result", JOptionPane.INFORMATION_MESSAGE);
}
}
View 不会保存数据,也不会执行任何计算或逻辑实现。它只负责与用户交互。看到“互动”这个词了吗?是的,我们将通过 View 类获取输入。但它不会将输入直接传递给模型,因为在 MVC 中, View 和模型不知道彼此的存在。
Controller
由于模型和 View 不相互交互,我们需要一个协调器来协调两个类(模型和 View )。
class MyController
{
private MyModel model;
private MyView view;
public MyController(MyModel model, MyView view){
this.model = model;
this.view = view;
}
public void start(){
int num = view.promptNumber();
model.checkEvenOdd(num);
view.displayResult(model.getOutcome());
}
}
Controller 将要求 View 与接收输入的用户进行交互,如果给出了输入。
然后将输入传递给模型进行处理。模型会将处理后的结果传回 Controller 。
Controller最终会将结果传递给View显示给用户。
运行示例:
为了驱动示例,我们创建了它们的实例并运行程序:
class MVCExample
{
public static void main(String[] args){
MyModel model = new MyModel();
MyView view = new MyView();
MyController controller = new MyController(model, view);
controller.start();
}
}
结论
I'm unsure whether it should be done from the model, the view, or the controller.
如果我们从逻辑上考虑每个类(模型、 View 和 Controller )的角色和职责,我会说 View 将负责接收输入。这也适用于控制台或 Swing 程序。
关于java - 从 MVC 架构中的对话框获取输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36127978/