java - 这是一种策略模式还是回调?

标签 java android design-patterns

今天我正在阅读有关 SOLID 的开闭原则,我记得的第一个示例是 Android 支持库中的 ViewDragHelper 类。

以下是类(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;
        }
    }
}

我想弄清楚它是不是strategy pattern 的实现。其实好像是的。有 Context(ViewDragHelper 类)和 Strategy 抽象(Callback 类)。但有两点:

  • 策略的具体实现委托(delegate)给图书馆的最终用户。
  • 策略实现的行为会影响Context(可以在tryCaptureView方法中夹住 View 位置或禁止拖动操作),而在Strategy pattern 描述 Strategy 似乎对 Context 没有任何影响(即只产生或使用一些数据)。

这是 Strategy 还是其他一些模式,或者只是像 Callback 这样的常见概念的实现?

最佳答案

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

不,它不是 classical definition 中的策略模式, 它是 Strategy 和 Observer Pattern 的组合. ViewDragHelper 的行为随 CallbackgetViewHorizo​​ntalDragRange()clampViewPositionHorizo​​ntal() 实现而改变(Strategy模式)。 ViewDragHelper 通过 onViewPositionChanged()ViewDragHelper 的当前状态通知给 Callback 的实例tryCaptureView() 实现(观察者模式)。

关于java - 这是一种策略模式还是回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52301563/

相关文章:

java - 简单的 string.equals 工作不正确 - Java

java - 下面的java代码有什么问题吗?

java - 如何结束程序,并阻止用户收到提示?

android - 如何解决 Late-enabling CheckJNI?

android - 在 Android Studio 中安装 com :android:support:percent:22. 2.1 库失败

java - Kotlin 中的赋值链?

android - 构建 Apk 错误 - 重复条目 : android/support/v4/database/DatabaseUtilsCompat. 类?

typescript 返回空发现模式问题

javascript - 需要深入了解如何构建 javascript fetch API

java - 覆盖时使用组合而不是继承