UI にボタン リスナーを追加するときに、2 つの異なるスタイルに遭遇しました。例として SWT を使用します。それにもかかわらず、J2ME、Flash Actionscript でも同様のコードを見ました。
スタイル 1:
b1.addSelectionListener(new SelectionListener()
{
public void widgetSelected(SelectionEvent e)
{
System.out.println("b1: ");
}
public void widgetDefaultSelected(SelectionEvent e)
{
System.out.println("Default selection");
}
});
b2.addSelectionListener(new SelectionListener()
{
public void widgetSelected(SelectionEvent e)
{
System.out.println("b2: ");
}
public void widgetDefaultSelected(SelectionEvent e)
{
System.out.println("Default selection");
}
});
スタイル 2:
b1.addSelectionListener(this);
b2.addSelectionListener(this);
public void widgetSelected(SelectionEvent e)
{
if (e.getSource() == b1)
{
System.out.println(b1);
}
else if (e.getSource() == b2)
{
System.out.println(b2);
}
}
public void widgetDefaultSelected(SelectionEvent e)
{
System.out.println("Default selection");
}
個人的には、マウス イベントを一元的に処理できる 2 番目のスタイルを好みます。どのスタイルが好きですか? なぜ?