實踐考慮處理輸入的這3個例子:最佳的處理組件的輸入Java中
/*EXAMPLE A*/
public class HandlingInputExampleA
{
private Label labelFromOtherClass; //injected by setter/constructor
private String myText = "hello ";
private int myInt = 1;
private void init()
{
Button button = new Button();
button.addClickListener(event -> labelFromOtherClass.setCaption(myText + myInt));
}
}
public class HandlingInputExampleB
{
private ClickListener inputHandler; //injected by setter/constructor
private String myText = "hello ";
private int myInt = 2;
private void init()
{
Button button = new Button();
button.addClickListener(inputHandler);
}
}
/*EXAMPLE B*/
public class HandlingInputExampleB
{
private ClickListener inputHandler; //injected by setter/constructor
private String myText = "hello ";
private int myInt = 2;
private void init()
{
Button button = new Button();
button.addClickListener(inputHandler);
}
}
public class InputHandlerB implements ClickListener
{
private HandlingInputExampleB exampleB; //injected by setter
private Label label; //injected by setter/constructor
@Override
public void buttonClick(ClickEvent event)
{
Button button = event.getButton();
if(button == exampleB.getButton())
{
label.setCaption(exampleB.getMyText() + exampleB.getMyInt());
}
}
}
/*EXAMPLE C*/
public class HandlingInputExampleC
{
private ClickListener inputHandler; //injected by setter/constructor
private String myText = "hello ";
private int myInt = 2;
private void init()
{
Button button = new Button();
button.setData(this);
button.addClickListener(inputHandler);
}
}
public class InputHandlerC implements ClickListener
{
private Label label; //injected by setter/constructor
@Override
public void buttonClick(ClickEvent event)
{
Button button = event.getButton();
if(button.getData() instanceof HandlingInputExampleC)
{
HandlingInputExampleC exampleC = (HandlingInputExampleC)button.getData();
label.setCaption(exampleC.getMyText() + exampleC.getMyInt());
}
}
}
我想我應該保持我的項目處理輸入的一種方式。大多數時候我創建一個類來處理輸入,並且在那裏注入所有需要的對象,因此與用戶輸入相關的每個操作都在一個地方進行管理。當然,我的項目變得越大,輸入處理程序類就越大,並且開始顯得有些雜亂。也許我錯過了更好的解決方案?請告訴我應該避免哪些示例?
去用最少的錯綜複雜和最容易理解你的項目的大小/把握。對於一個簡單的用戶界面來說,一些lambdas將會很好,大型項目會要求一些MV *模式。 – cfrick
謝謝你的回答!我一定會讀到MV *。這些例子中的任何一個從頭開始都模糊不清? – avix