本文借鉴于《重构-改善既有代码的设计》
下面的代码来自Android源码,分别是Android2.3以及Android4.0的Launcher代码。
2.3的实现代码如下:
上面的参数序列中,有一些问题:void onDrop(DragSource source, int x, int y, int xOffset, int yOffset, DragView dragView, Object dragInfo); void onDragEnter(DragSource source, int x, int y, int xOffset, int yOffset, DragView dragView, Object dragInfo); void onDragOver(DragSource source, int x, int y, int xOffset, int yOffset, DragView dragView, Object dragInfo); void onDragExit(DragSource source, int x, int y, int xOffset, int yOffset, DragView dragView, Object dragInfo);
- 参数很长,增加了理解的难度。
- 当需要添加一个属性时,需要修改所有的方法,添加一个参数。(这是一个非常不好的缺点)
- 随着参数的添加,参数序列有可能越来越长,而且变化频繁。
Android4.0对其进行了重构之后:
其对封装类型:void onDrop(DragObject dragObject); void onDragEnter(DragObject dragObject); void onDragOver(DragObject dragObject); void onDragExit(DragObject dragObject);
class DragObject { public int x = -1; public int y = -1; /** X offset from the upper-left corner of the cell to where we touched. */ public int xOffset = -1; /** Y offset from the upper-left corner of the cell to where we touched. */ public int yOffset = -1; /** This indicates whether a drag is in final stages, either drop or cancel. It * differentiates onDragExit, since this is called when the drag is ending, above * the current drag target, or when the drag moves off the current drag object. */ public boolean dragComplete = false; /** The view that moves around while you drag. */ public DragView dragView = null; /** The data associated with the object being dragged */ public Object dragInfo = null; /** Where the drag originated */ public DragSource dragSource = null; /** Post drag animation runnable */ public Runnable postAnimationRunnable = null; /** Indicates that the drag operation was cancelled */ public boolean cancelled = false; public DragObject() { } }