Code Fragment-方法的长参数序列可进行封装

本文借鉴于《重构-改善既有代码的设计》

下面的代码来自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);

上面的参数序列中,有一些问题:

  1. 参数很长,增加了理解的难度。
  2. 当需要添加一个属性时,需要修改所有的方法,添加一个参数。(这是一个非常不好的缺点)
  3. 随着参数的添加,参数序列有可能越来越长,而且变化频繁。

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() {
    }
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值