Is using OnClickListener() an example of Strategy

2019-07-13 08:38发布

问题:

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 at a time.
  3. OnClickListener is similar to a strategy where user code implements an strategy (method) to be invoked once button is clicked.
  4. Different implementations of OnClickListener can be passed to Button object during run time and behavior can be changed during run time. (Same button upon clicked may show a pop up with one implementation of OnClickListener and may send a request to server if another implementation of OnClickListener is passed.)

回答1:

Here is the intent of the Observer Pattern from page 293.

Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

Strictly speaking, the code example is not an Observer then, because the one-to-many relationship is rather one-to-one. However, I would not call this a Strategy either, per its intent from page 315.

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

Semantically, a listener is not an algorithm; i.e. responding to an event is a different purpose from performing a calculation. This purpose manifests syntactically where the onClick() method is void and therefore behaves more like a listener.

For that reason, I would call the code example a degenerate form of the Observer Pattern. It looks to me like an Observer attempt that didn't quite meet the qualifications. I wouldn't dignify the attempt by associating it with another pattern.