哔哩哔哩 Android 客户端——多媒体选择器 boxing 开源

2,677 阅读3分钟
原文链接: www.jianshu.com

开源过程是坎坷的,道路是曲折的,但前路是光明的。

Github链接--Bilibili/boxing

欢迎pypr,star,issue。

开端

整个工程的开始于2015年。
回顾过去,业务层和逻辑层是完全耦合的。
业务快速的迭代很容易令开发工作变快变糙变莽(技术水平未达标也是原因之一),一次改版可能要对原有的代码做侵入式修改,而根据开/闭原则,这是不可接受的。

旧问题

  • 由于设计欠缺优雅性导致功能扩展性差
  • 缺少单元测试无法保证程序的鲁棒性
  • 业务,逻辑和UI的代码耦合严重

2016年开始重构整个功能
目标

  • 业务层,逻辑层和UI层分离
  • 只依赖基础库
  • 易于业务扩展
  • 添加单元测试
  • 支持只使用Fragment

方案

  • 使用MVP模式
  • 只依赖support v4, v7
  • 通过接口和抽象类进行依赖反转
  • 使用Junit4 + Mokito + Espresso做测试

talk is free, show me the code.

时序图

启动Activity的情况


boxing_sequenece.png

概要类图


boxing_class.png

简洁起见,只画出两种关系,横线是组合,竖线是继承。根据依赖反转原则,横线指向的应该是抽象类或者接口(圆形)。所以,View层,Presenter层和Module层已经分离了。

设计接口

要只依赖于基础库,图片加载库和裁剪库的实现就要分离出去,通过接口的形式在内部使用。

public interface IBoxingMediaLoader {
    /**
     * display thumbnail images for a ImageView.
     *
     * @param img     the display ImageView.
     * @param absPath the absolute path to display.
     * @param width   the resize with for the image.
     * @param height  the resize height for the image.
     */
    void displayThumbnail(@NonNull ImageView img, @NonNull String absPath, int width, int height);

    /**
     * display raw images for a ImageView, need more work to do.
     *
     * @param img      the display ImageView.
     * @param absPath  the absolute path to display.
     * @param callback the callback for the load result.
     */
    void displayRaw(@NonNull ImageView img, @NonNull String absPath, IBoxingCallback callback);
}
  • 加载缩略图
    缩略图是根据界面可以知道resize宽高,不需要回调。
  • 加载原图
    原图可能很大,很长,所有是没有resize的,通过绝对路径去解析显示,同时提供加载成功/失败的回调。
public interface IBoxingCrop {

    /***
     * start crop operation.
     *
     * @param cropConfig  {@link BoxingCropOption}
     * @param path        the absolute path of media.
     * @param requestCode request code for the crop.
     */
    void onStartCrop(Context context, Fragment fragment, @NonNull BoxingCropOption cropConfig,
                     @NonNull String path, int requestCode);

    /**
     * get the result of cropping.
     *
     * @param resultCode the code in {@link android.app.Activity#onActivityResult(int, int, Intent)}
     * @param data       the data intent
     * @return the cropped image uri.
     */
    Uri onCropFinish(int resultCode, Intent data);
    }
  • 开始裁剪,启动者可能是Activity或Fragment,需要额外的裁剪参数
  • 裁剪结束,通过Intent取到结果Uri

分离实现库OK。

单元测试

单元测试的难易程度与耦合度成正比,简而言之,优雅的设计令单元测试的编写变得简单。
构造Mock类不再困难重重,接口方法实现单一功能,Presenter层和Model层的测试通过Junit4 + Mokito实现,UI层通过Espresso实现。

Only Fragment

参考Google MVP,Activity只作为Presenter和View连接的载体,用Fragment实现View接口,因此可以单独使用Fragment作为功能主体。

   // 初始化AbsBoxingPickerFragment
    Boxing.get().setupFragment(AbsBoxingPickerFragment, new Boxing.OnFinishListener() {
        @Override
        public void onFinish(Intent intent, @Nullable List<BaseMedia> medias) {
           // 通过回调接口取到结果         
        }
    });

最后总结

抽象能力非常重要,需要不断地练习。

UML图很重要,强烈推荐Bob大叔的UML:Java程序员指南(双语版),畅快淋漓的阅读快感。