责任链模式介绍
责任链模式(Iterator Pattern),是行为型设计模式之一。什么是“链”?我们将多个节点首尾相连所构成的模型称为链。
将每一个节点看做是一个对象,每一个对象拥有不同的处理逻辑,将一个请求从链式的首端发出,沿着链的路径依次传递给每一个节点对象,直到有对象处理这个请求为止,这种模式称为责任链模式。
责任链模式的定义
使多个对象都有机会处理请求,从而避免了请求的发送者和接收者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递该请求,直到有对象处理它为止。
责任链模式的使用场景
多个对象可以处理同一请求,但具体由哪个对象处理则在运行时动态决定。
在请求处理者不明确的情况下向多个对象中的一个提交一个请求。
需要动态指定一组对象处理请求。
Android源码中责任链模式
责任链模式在源码中比较类似的实现莫过于对于事件的处理,用户接触屏幕时,Android都会将对应的事件包装成一个事件对象,从ViewTree的顶部至上而下地分发传递。关于事件的包装为命令模式中,关于IMS对事件的处理为访问者模式,在责任链模式中主要看ViewGroup如何将事件派发到子View,我们知道ViewGroup中执行事件派发的方法是dispatchTouchEvent,在该方法中对事件进行了统一的分发。
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
}
// If the event targets the accessibility focused view and this is it, start
// normal event dispatch. Maybe a descendant is what will handle the click.
//对于辅助功能的事件处理
if (ev.isTargetAccessibilityFocus() && isAccessibilityFocusedViewOrHost()) {
ev.setTargetAccessibilityFocus(false);
}
if (ViewDebugManager.DEBUG_MOTION) {
Log.d(TAG, "(ViewGroup)dispatchTouchEvent 1: ev = " + ev + ",mFirstTouchTarget = "
+ mFirstTouchTarget + ",this = " + this);
}
boolean handled = false;
if (onFilterTouchEventForSecurity(ev)) {
final int action = ev.getAction();
final int actionMasked = action & MotionEvent.ACTION_MASK;
// Handle an initial down.
//处理原始的DOWN事件
if (actionMasked == MotionEvent.ACTION_DOWN) {
// Throw away all previous state when starting a new touch gesture.
// The framework may have dropped the up or cancel event for the previous gesture
// due to an app switch, ANR, or some other state change.
//这里主要是在新事件开始时处理完上一个事件。
cancelAndClearTouchTargets(ev);
resetTouchState();
}
// Check for interception.
//检查拦截
final boolean intercepted;
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!disallowIntercept) {
intercepted = onInterceptTouchEvent(ev);
/// M : add log to help debugging
if (intercepted == true && ViewDebugManager.DEBUG_TOUCH) {
Log.d(TAG, "Touch event was intercepted event = " + ev
+ ",this = " + this);
}
//恢复事件防止其改变
ev.setAction(action); // restore action in case it was changed
} else {
intercepted = false;
}
} else {
// There are no touch targets and this action is not an initial down
// so this view group continues to intercept touches.
intercepted = true;
}
// If intercepted, start normal event dispatch. Also if there is already
// a view that is handling the gesture, do normal event dispatch.
//如果事件被拦截了,则进行正常的事件分发
if (intercepted || mFirstTouchTarget != null) {
ev.setTargetAccessibilityFocus(false);
}
// Check for cancelation.
//检查事件是否取消
final boolean canceled = resetCancelNextUpFlag(this)
|| actionMasked == MotionEvent.ACTION_CANCEL;
// Update list of touch targets for pointer down, if needed.
//如果有必要的话,为Down事件检查所有的目标对象
final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
TouchTarget newTouchTarget = null;
boolean alreadyDispatchedToNewTouchTarget = false;
//如果事件未被取消并未被拦截
if (!canceled && !intercepted) {
// If the event is targeting accessiiblity focus we give it to the
// view that has accessibility focus and if it does not handle it
// we clear the flag and dispatch the event to all children as usual.
// We are looking up the accessibility focused host to avoid keeping
// state since these events are very rare.
//如果有辅助功能的参与,则直接将事件投递到对应的View,否则将事件分发给多有的子View。
View childWithAccessibilityFocus = ev.isTargetAccessibilityFocus()
? findChildWithAccessibilityFocus() : null;
//如果事件为起始事件
if (actionMasked == MotionEvent.ACTION_DOWN
|| (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
|| actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
final int actionIndex = ev.getActionIndex(); // always 0 for down
final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex)
: TouchTarget.ALL_POINTER_IDS;
// Clean up earlier touch targets for this pointer id in case they
// have become out of sync.
removePointersFromTouchTargets(idBitsToAssign);
final int childrenCount = mChildrenCount;
//如果Touchtarget为空并且子元素不为0
if (newTouchTarget == null && childrenCount != 0) {
final float x = ev.getX(actionIndex);
final float y = ev.getY(actionIndex);
// Find a child that can receive the event.
// Scan children from front to back.
//由上至下寻找一个可以接收该事件的子View
final ArrayList<View> preorderedList = buildTouchDispatchChildList();
final boolean customOrder = preorderedList == null
&& isChildrenDrawingOrderEnabled();
final View[] children = mChildren;
//遍历子元素
for (int i = childrenCount - 1; i >= 0; i--) {
final int childIndex = getAndVerifyPreorderedIndex(
childrenCount, i, customOrder);
final View child = getAndVerifyPreorderedView(
preorderedList, children, childIndex);
// If there is a view that has accessibility focus we want it
// to get the event first and if not handled we will perform a
// normal dispatch. We may do a double iteration but this is
// safer given the timeframe.
if (childWithAccessibilityFocus != null) {
if (childWithAccessibilityFocus != child) {
continue;
}
childWithAccessibilityFocus = null;
i = childrenCount - 1;
}
//如果这个子元素无法接收Pointer Event或这个事件压根就没有落在子元素的边界范围内
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
ev.setTargetAccessibilityFocus(false);
//跳出该次循环继续遍历
continue;
}
//找到Event该由哪一个子元素持有。
newTouchTarget = getTouchTarget(child);
if (ViewDebugManager.DEBUG_MOTION) {
Log.d(TAG, "(ViewGroup)dispatchTouchEvent to child 3: child = "
+ child + ",childrenCount = " + childrenCount + ",i = " + i
+ ",newTouchTarget = " + newTouchTarget
+ ",idBitsToAssign = " + idBitsToAssign);
}
if (newTouchTarget != null) {
// Child is already receiving touch within its bounds.
// Give it the new pointer in addition to the ones it is handling.
newTouchTarget.pointerIdBits |= idBitsToAssign;
break;
}
resetCancelNextUpFlag(child);
//投递事件执行触摸操作。
//如果子元素还是一个ViewGroup,则递归调用重复此过程。
//如果子元素是一个View,那么则会调用View的dispatchTouchEvent,并最终由onTouchEvent处理。
if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
// Child wants to receive touch within its bounds.
//子View在其边界范围内接收事件
mLastTouchDownTime = ev.getDownTime();
if (preorderedList != null) {
// childIndex points into presorted list, find original index
for (int j = 0; j < childrenCount; j++) {
if (children[childIndex] == mChildren[j]) {
mLastTouchDownIndex = j;
break;
}
}
} else {
mLastTouchDownIndex = childIndex;
}
mLastTouchDownX = ev.getX();
mLastTouchDownY = ev.getY();
newTouchTarget = addTouchTarget(child, idBitsToAssign);
alreadyDispatchedToNewTouchTarget = true;
break;
}
// The accessibility focus didn't handle the event, so clear
// the flag and do a normal dispatch to all children.
ev.setTargetAccessibilityFocus(false);
}
if (preorderedList != null) preorderedList.clear();
}
//如果发现没有子元素可以持有该次事件
if (newTouchTarget == null && mFirstTouchTarget != null) {
// Did not find a child to receive the event.
// Assign the pointer to the least recently added target.
newTouchTarget = mFirstTouchTarget;
while (newTouchTarget.next != null) {
newTouchTarget = newTouchTarget.next;
}
newTouchTarget.pointerIdBits |= idBitsToAssign;
}
}
}
// Dispatch to touch targets.
if (mFirstTouchTarget == null) {
// No touch targets so treat this as an ordinary view.
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
} else {
// Dispatch to touch targets, excluding the new touch target if we already
// dispatched to it. Cancel touch targets if necessary.
TouchTarget predecessor = null;
TouchTarget target = mFirstTouchTarget;
while (target != null) {
final TouchTarget next = target.next;
if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
handled = true;
} else {
final boolean cancelChild = resetCancelNextUpFlag(target.child)
|| intercepted;
if (dispatchTransformedTouchEvent(ev, cancelChild,
target.child, target.pointerIdBits)) {
handled = true;
}
if (ViewDebugManager.DEBUG_MOTION) {
Log.d(TAG, "dispatchTouchEvent middle 5: cancelChild = " + cancelChild
+ ",mFirstTouchTarget = " + mFirstTouchTarget + ",target = "
+ target + ",predecessor = " + predecessor + ",next = " + next
+ ",this = " + this);
}
if (cancelChild) {
if (predecessor == null) {
mFirstTouchTarget = next;
} else {
predecessor.next = next;
}
target.recycle();
target = next;
continue;
}
}
predecessor = target;
target = next;
}
}
// Update list of touch targets for pointer up or cancel, if needed.
if (canceled
|| actionMasked == MotionEvent.ACTION_UP
|| actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
resetTouchState();
} else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) {
final int actionIndex = ev.getActionIndex();
final int idBitsToRemove = 1 << ev.getPointerId(actionIndex);
removePointersFromTouchTargets(idBitsToRemove);
}
}
if (!handled && mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1);
}
return handled;
}
这里主要看看dispatchTransformedTouchEvent 方法是如何调度子元素dispatchTouchEvent 方法的。
/**
* Transforms a motion event into the coordinate space of a particular child view,
* filters out irrelevant pointer ids, and overrides its action if necessary.
* If child is null, assumes the MotionEvent will be sent to this ViewGroup instead.
*/
private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
View child, int desiredPointerIdBits) {
final boolean handled;
// Canceling motions is a special case. We don't need to perform any transformations
// or filtering. The important part is the action, not the contents.
final int oldAction = event.getAction();
if (ViewDebugManager.DEBUG_MOTION) {
Log.d(TAG, "dispatchTransformedTouchEvent 1: event = " + event + ",cancel = "
+ cancel + ",oldAction = " + oldAction + ",desiredPointerIdBits = "
+ desiredPointerIdBits + ",mFirstTouchTarget = " + mFirstTouchTarget
+ ",child = " + child + ",this = " + this);
}
//如果事件被取消
if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {
event.setAction(MotionEvent.ACTION_CANCEL);
//如果没有子元素
if (child == null) {
//那么就直接调用父类的dispatchTouchEvent ,注意,这里的父类终会为View类
handled = super.dispatchTouchEvent(event);
} else {
//如果有子元素则传递cancel事件
handled = child.dispatchTouchEvent(event);
}
event.setAction(oldAction);
return handled;
}
// Calculate the number of pointers to deliver.
//计算即将被传递的点的数量
final int oldPointerIdBits = event.getPointerIdBits();
final int newPointerIdBits = oldPointerIdBits & desiredPointerIdBits;
// If for some reason we ended up in an inconsistent state where it looks like we
// might produce a motion event with no pointers in it, then drop the event.
//如果事件没有相应的点,那么就丢弃该事件
if (newPointerIdBits == 0) {
Log.i(TAG, "Dispatch transformed touch event without pointers in " + this);
return false;
}
// If the number of pointers is the same and we don't need to perform any fancy
// irreversible transformations, then we can reuse the motion event for this
// dispatch as long as we are careful to revert any changes we make.
// Otherwise we need to make a copy.
//声明临时变量保存坐标转换后的MotionEvent
final MotionEvent transformedEvent;
//如果事件点的数量一致
if (newPointerIdBits == oldPointerIdBits) {
//子元素为空或者子元素有一个单位矩阵
if (child == null || child.hasIdentityMatrix()) {
//再次区分子元素为空的情况
if (child == null) {
//为空则调用父类dispatchTouchEvent
handled = super.dispatchTouchEvent(event);
} else {
//否则尝试获取xy方向上的偏移量(如果通过scrollTo或scrollBy对子视图进行滚动的话)
final float offsetX = mScrollX - child.mLeft;
final float offsetY = mScrollY - child.mTop;
//将MotionEvent进行坐标变换
event.offsetLocation(offsetX, offsetY);
//再将变换后的MotionEvent传递给子元素
handled = child.dispatchTouchEvent(event);
//复位MotionEvent以便之后再次使用
event.offsetLocation(-offsetX, -offsetY);
}
//如果通过以上的逻辑判断,当前事件被持有则可以直接返回。
return handled;
}
transformedEvent = MotionEvent.obtain(event);
} else {
transformedEvent = event.split(newPointerIdBits);
}
// Perform any necessary transformations and dispatch.
if (child == null) {
handled = super.dispatchTouchEvent(transformedEvent);
} else {
final float offsetX = mScrollX - child.mLeft;
final float offsetY = mScrollY - child.mTop;
transformedEvent.offsetLocation(offsetX, offsetY);
if (! child.hasIdentityMatrix()) {
transformedEvent.transform(child.getInverseMatrix());
}
handled = child.dispatchTouchEvent(transformedEvent);
}
if (ViewDebugManager.DEBUG_MOTION) {
Log.d(TAG, "dispatchTransformedTouchEvent 3 to child " + child + ",handled = "
+ handled + ",mScrollX = " + mScrollX + ",mScrollY = " + mScrollY
+ ",mFirstTouchTarget = " + mFirstTouchTarget + ",transformedEvent = "
+ transformedEvent + ",this = " + this);
}
// Done.
transformedEvent.recycle();
return handled;
}
ViewGroup事件投递的递归调用就类似于一条责任链,一旦其寻找到责任者,那么将由责任者持有并消费掉该次事件,具体的体现在View的onTouchEvent方法中返回值的设置,如果onTouchEvent返回false,那么意味着当前View不会是该次事件的责任人,将不会对其持有,如果为true则相反,此时View会持有该事件并不再向外传递。
责任链模式与其说在Android中应用不如说在Java中的应用,毕竟上层应用大多都是基于Java的,而设计模式也是针对Java的,可以使用责任链模式替代各种条件分支或条件判断语句,不过多数情况下是多此一举。我们知道Broadcast可以被分为两种,一种是Normal Broadcast普通广播,另一种是Ordered Broadcast 有序广播,普通广播是异步的,发出时可以被所有的接收者收到。
而有序广播则是根据优先级依次传播的,直到有接收者将其终止或所有接收者都不终止它,有序广播的这一特性与责任链模式接近,通过它可以实现一种全局责任链事件处理。
参考《Android源码设计模式》