Android模块化设计方案之使用代理模式解耦

1,265 阅读4分钟

本篇是Android模块化设计方案的第三篇,也是对第一篇中ThridLibs Proxy模块进行说明。

很多人觉得对那些优秀的第三方依赖库再次封装是一件多余的事情,因为这些库可能出自大神/大厂,或有非常高的star并且使用起来十分稳定,可以在项目中直接拿来使用。当然每个开发者都有自己的态度,我也只是根据以往的经验,表达一下自己的看法。

作为从了解四大组件就不愁找不到工作的互联网大时代中一路走来的Android老鸟,经历了网路请求框架从HttpConnection到Volley再到OkHttp,也经历了图片加载框架从UniversalImageLoader到Picasso再到Gilde,技术的迭代随时都会发生。让项目架构具有良好的扩展性是在设计之初就需要考虑的东西。

那么接下来我用一个简单的demo来演示一下如何使用代理模式对第三方框架进行解耦。

现在我们有一个名为thirdlib的模块,为我们提供图片加载功能。

public class ImageLoader {
   public void load(ImageView imageView, String url) {
       //TODO 实现图片加载功能
   }
}

第一步:我们创建了一个新的模块thridlibproxy,并且该模块依赖于thirdlib,我们在该模块中创建包私有的接口ImageLoaderInterface,这个接口中把thirdlib模块中提供的功能抽象为接口:

interface ImageLoaderInterface {
   void loadImage(ImageView imageView, String url);
}

第二步:创建包私有的接口的实现类ImageLoaderOneImpl,类中图片加载的业务逻辑是通过调用thirdlib中的ImageLoader类实现的。:

class ImageLoaderOneImpl implements ImageLoaderInterface {

   private ImageLoader imageLoader = new ImageLoader();

   @Override
   public void loadImage(ImageView imageView, String url) {
       imageLoader.load(imageView, url);
   }
}

第三步:我们提供一个供外部调用的ImageLoaderOneImpl接口代理类ImageLoaderProxy:

public class ImageLoaderProxy implements ImageLoaderInterface {

    private static ImageLoaderProxy instance;

    public static ImageLoaderProxy getInstance() {
        if (instance == null) {
            synchronized (ImageLoaderProxy.class) {
                if (instance == null) {
                    instance = new ImageLoaderProxy();
                    instance.init();
                }
            }
        }
        return instance;
    }

    private ImageLoaderInterface loader;

    private void init() {
        this.loader = new ImageLoaderOneImpl();
        //TODO 做一些其他初始化操作
    }

    private ImageLoaderProxy() {

    }

    @Override
    public void loadImage(ImageView imageView, String url) {
        loader.loadImage(imageView, url);
    }
}

最后我们就可以通过ImageLoaderProxy中提供的loadImage方法进行图片的加载了。

看到这里有些盆友就会问了,在第二步的时候,我们就完成了thirdlib的封装工作,为什么还要有第三步?还有我写一个单例类直接对thirdlib进行封装不就行了,为什么还要抽象出接口?

原因很简单,为的就是尽可能的满足软件设计七大原则中的第一个:开闭原则

一个好的软件设计,需要对拓展开放,对修改关闭。我们在设计之初就要想到,在更换图片加载框架之后如何最大程度上满足开闭原则。

如果直接对thirdlib进行封装,是面向类的开发而不是面向接口。如果此时更换图片加载类库,那必然会对封装出来的类进行大量的修改,把原来的实现替换为新的实现。

使用代理模式的好处就是,我新创建一个被代理的类ImageLoaderTwoImpl:

class ImageLoaderTwoImpl implements ImageLoaderInterface {

    private NewImageLoader newImageLoader = new NewImageLoader();

    @Override
    public void loadImage(ImageView imageView, String url) {
        newImageLoader.newLoad(imageView, url);
    }
}

然后只需要对第三步中的被代理类进行替换就行了。

//this.loader = new ImageLoaderOneImpl();
this.loader = new ImageLoaderTwoImpl();

在想要达到相同效果的时候,最大程度的满足了开闭原则。

我们业务层模块也和第三方库实现了完全的解耦,我不需要知道thridlibproxy是如何帮我完成图片加载工作的,但是只要调用它提供的方法就完事儿的,这也符合软件设计七大原则中的:最少知道原则

关于为何以及怎么通过代理调用第三方依赖库,到这里就介绍完毕了,赶快动手试试吧~

image.png

试想一下,如果初期规划的不够全面(这也很常见),后期需要对抽象出来的接口新增方法,如何才能最大程度实现开闭原则?

我只想说:原则是死的,人是活的😹

如果该文章能够帮到你,欢迎点赞评论和关注,一起交流探讨~