介绍:责任链模式(Iterator Pattern),是行为型设计模式之一。
定义:使多个对象都有机会处理请求,从而避免了请求的发送者和接受者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递该请求,直到有对象处理它为止。
使用场景:
多个对象可以处理同一个请求,但具体由哪个对象处理则在运行时动态决定。
在请求处理者不明确的情况下向多个对象中的一个提交一个请求。
需要动态指定一组对象处理请求。
UML类图
// 抽象处理者
public abstract class Handler {
protected Handler successor;
public abstract void handleRequest(String condition);
}
具体的处理者1
// 具体的处理者1
public class ConcreteHandler1 extends Handler{
@Override
public void handleRequest(String condition) {
if ("ConcreteHandler1".equalsIgnoreCase(condition)) {
System.out.println("ConcreteHandler1 handler");
return;
}
successor.handleRequest(condition);
}
}
具体的处理者2
// 具体的处理者2
public class ConcreteHandler2 extends Handler{
@Override
public void handleRequest(String condition) {
if ("ConcreteHandler2".equalsIgnoreCase(condition)) {
System.out.println("ConcreteHandler2 handler");
return;
}
successor.handleRequest(condition);
}
}
客户端
// 客户端
public class Client {
public static void main(String[] args) {
Handler handler1 = new ConcreteHandler1();
Handler handler2 = new ConcreteHandler2();
// 设置handler1的下一个节点
handler1.successor = handler2;
// 设置handler2的下一个节点
handler2.successor = handler1;
// 处理请求
handler1.handleRequest("ConcreteHandler2");
}
}
Handler:抽象处理者角色,声明一个请求处理方法,并在其中保持一个对下一个处理节点Handler对象的引用。
ConcreteHandler:具体处理者角色,对请求进行处理,如果不能处理则将该请求转发给下一个节点上的处理对象。
案例简单实现
下面以小明申请报销费用为例。
假设小明向组长申请报销5万元的费用,组长一看是一笔不小的数目,他没有权限审批,于是组长就拿着票据去找部门主管,主管一看要报这么多钱,自己权限内只能批5千以下的费用,完成超出了自己的权限范围,于是主管又跑去找经理,经理一看二话不说就直接拿着票据奔向了老板办公室,因为他只能批一万以下的费用。
这个例子中,小明只与组长产生了关系,后续具体由谁处理票据,小明并不关心,唯一在乎的是报账的结果。上例中每一类人代表这条链上的一个节点,小明是请求的发起者,而老板是处于链条顶端的类。
先声明一个抽象的领导类
public abstract class Leader {
protected Leader nextHandler; // 上一级领导处理者
// 处理报销请求
public void handleRequest(int money) {
if (money < limit()) {
handle(money);
return;
}
if (nextHandler != null) {
nextHandler.handleRequest(money);
} else {
System.out.println(this.getClass().getCanonicalName() + " 权限不足");
}
}
// 处理报账行为
protected abstract void handle(int money);
// 自身能批复的额度权限
protected abstract int limit();
}
在这个抽象的领导类中只做了两件事,一是定义了两个接口方法来确定一个领导者应有的行为和属性,二是声明一个处理报账请求的方法来确定当前领导是否有能力处理报账请求,如果没有权限,则将该请求转发给上级领导处理。
各个具体的领导者:
// 组长
public class GroupLeader extends Leader {
@Override
protected void handle(int money) {
System.out.println("组长批复报销:" + money);
}
@Override
protected int limit() {
return 1000;
}
}
// 主管
public class Director extends Leader {
@Override
protected void handle(int money) {
System.out.println("主管批复报销:" + money);
}
@Override
protected int limit() {
return 5000;
}
}
// 经理
public class Manager extends Leader {
@Override
protected void handle(int money) {
System.out.println("经理批复报销:" + money);
}
@Override
protected int limit() {
return 10000;
}
}
// 老板
public class Boss extends Leader {
@Override
protected void handle(int money) {
System.out.println("老板批复报销:" + money);
}
@Override
protected int limit() {
return Integer.MAX_VALUE;
}
}
接下来就是小明同学发起报账申请了
public class XiaoMin {
public static void main(String[] args) {
// 构造各个领导者
Leader group = new GroupLeader();
Leader director = new Director();
Leader manager = new Manager();
Leader boss = new Boss();
// 设置上一级领导处理者对象
group.nextHandler = director;
director.nextHandler = manager;
manager.nextHandler = boss;
// 发起报账申请
group.handleRequest(50000);
}
}
Android源码中的责任链模式的实现
责任链模式在Android源码中比较类似的实现莫过于对事件的分发处理,每当用户接触屏幕时,Android都会将对应的事件包装成一个事件对象从ViewTree的顶部至上而下地分发传递。
接下来主要来看看ViewGroup中是如何将事件派发到子View的。ViewGroup中执行事件派发的方法是dispatchTouchEvent,在该方法中对事件进行了同一的分发:
public boolean dispatchTouchEvent(MotionEvent ev) {
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
}
// 对辅助功能的事件处理
if (ev.isTargetAccessibilityFocus() && isAccessibilityFocusedViewOrHost()) {
ev.setTargetAccessibilityFocus(false);
}
boolean handled = false;
if (onFilterTouchEventForSecurity(ev)) {
final int action = ev.getAction();
final int actionMasked = action & MotionEvent.ACTION_MASK;
// 处理原始的DOWN事件
if (actionMasked == MotionEvent.ACTION_DOWN) {
// 这里主要是在新事件开始时处理完上一个事件
cancelAndClearTouchTargets(ev);
resetTouchState();
}
// 检查事件拦截
final boolean intercepted;
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!disallowIntercept) {
intercepted = onInterceptTouchEvent(ev);
// 恢复事件防止其改变
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 || mFirstTouchTarget != null) {
ev.setTargetAccessibilityFocus(false);
}
// 检查事件是否取消
final boolean canceled = resetCancelNextUpFlag(this)
|| actionMasked == MotionEvent.ACTION_CANCEL;
// 如果有必要的话,为DOWN事件检查所有的目标对象
final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
TouchTarget newTouchTarget = null;
boolean alreadyDispatchedToNewTouchTarget = false;
// 如果事件未被取消未被拦截
if (!canceled && !intercepted) {
// 如果有辅助功能的参与,则直接将事件投递到对应的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为空且子View不为0
if (newTouchTarget == null && childrenCount != 0) {
final float x = ev.getX(actionIndex);
final float y = ev.getY(actionIndex);
// 由上至下去寻找一个可以接收该事件的子View
final ArrayList<View> preorderedList = buildTouchDispatchChildList();
final boolean customOrder = preorderedList == null
&& isChildrenDrawingOrderEnabled();
final View[] children = mChildren;
// 遍历子View
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;
}
// 如果这个子View无法接收Pointer Event或者这个事件点压根没有落在子View的边界范围内
if (!child.canReceivePointerEvents()
|| !isTransformedTouchPointInView(x, y, child, null)) {
ev.setTargetAccessibilityFocus(false);
continue;
}
// 找到Event该由哪个子View持有
newTouchTarget = getTouchTarget(child);
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);
// 投递事件执行触摸操作
// 如果子View还是一个ViewGroup,则递归调用重复次过程
// 如果子元素是一个View,那么则会调用View的dispatchTouchEvent,最终由onTouchEvent处理
if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
// 子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();
}
// 如果发现没有子View可以持有该次事件
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 (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方法如何调度子View的dispatchTouchEvent方法的
private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
View child, int desiredPointerIdBits) {
final boolean handled;
// 如果事件被取消
final int oldAction = event.getAction();
if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {
event.setAction(MotionEvent.ACTION_CANCEL);
// 如果没有子View
if (child == null) {
// 那么就直接调用父类的dispatchTouchEvent,注意,这里的父类终会为View类
handled = super.dispatchTouchEvent(event);
} else {
// 如果有子View则传递CANCEL事件
handled = child.dispatchTouchEvent(event);
}
event.setAction(oldAction);
return handled;
}
// 计算即将被传递的点的数量
final int oldPointerIdBits = event.getPointerIdBits();
final int newPointerIdBits = oldPointerIdBits & desiredPointerIdBits;
// 如果事件没有相应的点,那么就丢弃该事件
if (newPointerIdBits == 0) {
return false;
}
// 如果事件点的数量一致
final MotionEvent transformedEvent;
if (newPointerIdBits == oldPointerIdBits) {
// 子View为空或者子View有一个单位矩阵
if (child == null || child.hasIdentityMatrix()) {
// 如果子View为空的情况
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转递给子View
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);
}
// Done.
transformedEvent.recycle();
return handled;
}
ViewGroup事件投递的递归调用就类似一条责任链,一旦其寻找到责任者,那么将由责任者持有并消费掉该次事件,具体地体现在View的 onTouchEvent 方法中返回值的设置,如果 onTouchEvent 返回false,那么意味着当前View不会是该次事件的责任人,将不会对其持有,如果为true则相反,此时View会持有该事件并不再向外传递。
如果我的文章对您有帮助,不妨点个赞鼓励一下(^_^)
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。