dimanche 24 février 2019

Is Android's View.OnClickListener usage in Views is an example of Strategy pattern?

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 :

  1. Here we see Button class does not has a list of listeners(Observers) but can have only one listener.
  2. It delegates a part of method to its instance member : listener.
  3. OnClickListener is similar to a strategy where user code implements an strategy (method) to be invoked once button is clicked.

Aucun commentaire:

Enregistrer un commentaire