简体   繁体   中英

Is this a strategy pattern or just a callback?

I was reading about SOLID's Open/Closed Principle today and first example I remembered was ViewDragHelper class in Android support library.

Here are the details of the class:

// allowing a user to drag and reposition views
public class ViewDragHelper {
    private final Callback mCallback;

    public static ViewDragHelper create(..., Callback cb)

    public abstract static class Callback {
        public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) { }

        public int getViewHorizontalDragRange(View child) {
            return 0;
        }

        public abstract boolean tryCaptureView(View child, int pointerId);

        public int clampViewPositionHorizontal(View child, int left, int dx) {
            return 0;
        }
    }
}

I'm trying to figure out is it an implementation of strategy pattern . Actually it seems like it is. There is the Context ( ViewDragHelper class) and the Strategy abstraction ( Callback class). But there are two points:

  • Concrete implementation of the strategy is delegated to an end-user of the library.
  • Behavior of the strategy implementation affects the Context (you can clamp the view position or forbid drag operation in tryCaptureView method), while in Strategy pattern description a Strategy seems don't have any impact on the Context (ie only produce or consume some data).

Is this a Strategy or some other pattern or just implementation of such a common concepts like Callback ?

Is this a Strategy or some other pattern or just implementation of such a common concepts like Callback ?

No, it isn't Strategy Pattern in its classical definition , it is rather a combination of both, Strategy and Observer Pattern . ViewDragHelper 's behaviour changes with Callback 's getViewHorizontalDragRange() and clampViewPositionHorizontal() implementations ( Strategy Pattern ). And ViewDragHelper notifies a Callback 's instance about ViewDragHelper 's current state through onViewPositionChanged() and tryCaptureView() implementations (Observer Pattern).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM