今天我正在阅读有关 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 likeCallback
?
不,它不是 classical definition 中的策略模式, 它是 Strategy 和 Observer Pattern 的组合. ViewDragHelper
的行为随 Callback
的 getViewHorizontalDragRange()
和 clampViewPositionHorizontal()
实现而改变(Strategy模式)。 ViewDragHelper
通过 onViewPositionChanged()
和 将
实现(观察者模式)。ViewDragHelper
的当前状态通知给 Callback
的实例tryCaptureView()
关于java - 这是一种策略模式还是回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52301563/