Is OnClickListener in android an example of Strategy pattern ? In another Stackoverflow question accepted answer says it is Observer Pattern.
Similar Code to understand the question.
public interface OnClickListener{
void onClick(View view);
}
public class Button extends View{
private OnClickListener listener;
void clicked(){
//some code
if(listener != null){
listener.onClick(this);
}
//some other code
}
public void setOnClickListener(OnClickListener listener){
this.listener = listener;
}
}
My reasoning to believe its strategy pattern and not observer pattern :
- Here we see
Button
class does not has a list of listeners(Observers) but can have only one listener. - It delegates a part of method to its instance member : listener at a time.
OnClickListener
is similar to a strategy where user code implements an strategy (method) to be invoked once button is clicked.- Different implementations of
OnClickListener
can be passed toButton
object during run time and behavior can be changed during run time. (Same button upon clicked may show a pop up with one implementation ofOnClickListener
and may send a request to server if another implementation ofOnClickListener
is passed.)