我發現人們經常使用一個處理多個事件源(對於幾個按鈕的exeampl一個OnClickHandler(視圖v))。一個OnClickHandler與開關/案件與匿名內部類
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mButton1 = (Button) v.findViewById(R.id.button1);
mButton2 = (Button) v.findViewById(R.id.button2);
mButton1.setOnClickListener(this);
mButton2.setOnClickListener(this);
}
@Override
public boolean onClick(final View v) {
if (v == mButton1) {
title = getString(R.string.action1Title);
defaultText = getText1();
} else if (v == mUriLabel) {
title = getString(R.string.action2Title);
defaultText = getText2;
}
// Here some common code
}
在這裏,我們有兩個功能:然後處理程序取決於參數v
一個分支,比如選擇。 onCreateView只是將所有事件導向單個處理程序。而onClick是由它自己處理的,它應該確定事件的來源並且轉到一個分支或另一個分支。
另一方面,我們可以在實現onClick的anonymouse內部類中實例化。就像這樣:
// In cases, when there is some common part,
// we need additional interface to separate common part and
// customizable action.
interface ICustomAction {
void doSomeAction();
}
class BaseHandler implements View.ClickListener {
ICustomAction mCustomAction;
// Constructor which receive specific action
CommonHandler(ICustomAction customAction) {
mCustomAction = customAction;
}
@Override
public boolean onClick(final View v) {
mCustomAction.doSomeAction();
// Here some common code
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mButton1 = (Button) v.findViewById(R.id.button1);
mButton1.setOnClickListener(new BaseHandler(new ICustomAction() {
@Override
void doSomeAction() {
title = getString(R.string.action1Title);
defaultText = getText1();
}
}));
mButton2 = (Button) v.findViewById(R.id.button2);
mButton2.setOnClickListener(new BaseHandler(new ICustomAction() {
@Override
void doSomeAction() {
title = getString(R.string.action2Title);
defaultText = getText2();
}
}));
在這裏,我們有更復雜的通信類,但局部的附近註冊處理的具體差異。我們用一個虛擬函數(定義在ICustomAction接口中)替換開關/外殼。
而且IDE可以簡化表示這樣的匿名類,並顯示他們像拉姆達功能
mButton2.setOnClickListener(new BaseHandler(() ->{
title = getString(R.string.action2Title);
defaultText = getText2();
}));
所以,登記處理變得更加緊湊,但還是老樣子包含有意義的差異。
問題是,在switch/case statment中使用一個處理程序以及使用anonymouse內部類的方法更可取的原因是什麼?
如果您根據類似的實現進行比較,它會更有意義。例如。如果你已經使用了'mButton1.setOnClickListener(新的View.OnClickListener'而不是這個自制的'複雜'層次結構 –
我想展示一些常見代碼的例子,它總是執行直接繼承'View.OnClickListener'導致代碼重複在這種情況下 – Piroxiljin