外观模式

2019-02-20  本文已影响0人  1dot4

介绍

外观模式在开发过程中的运用频率非常高,尤其是第三方SDK。通过一个外观类是的整个系统的接口只有一个统一的高层接口,这样能降低用户的使用成本,也对用户屏蔽了很多实现细节。

UML类图

facade.png

Android源码中的外观模式

在开发中,Context是最重要的一个类型。它只是一个定义了很多接口的抽象类,这些接口的实现并不在Context及其子类,而是通过其他子系统完成。例如,startActivity的真正实现是通过Instrumentation.execStartActivity。Context只是做了一个高层次的统一封装,它的真正实现是在ContextImpl类,ContextImpl就是外观类。

public class ContextWrapper extends Context {
    Context mBase;

    public ContextWrapper(Context base) {
        mBase = base;
    }
    
 
    protected void attachBaseContext(Context base) {
        if (mBase != null) {
            throw new IllegalStateException("Base context already set");
        }
        mBase = base;
    }

    public Context getBaseContext() {
        return mBase;
    }

    @Override
    public AssetManager getAssets() {
        return mBase.getAssets();
    }

    @Override
    public Resources getResources() {
        return mBase.getResources();
    }

    @Override
    public PackageManager getPackageManager() {
        return mBase.getPackageManager();
    }

    @Override
    public ContentResolver getContentResolver() {
        return mBase.getContentResolver();
    }
  
    //省略其他代码
}

如上述代码所示,ContextImpl封装了很多不同子系统的操作。用户通过Context这个接口统一进行与Android系统的交互,不需要对每个子系统进行了解,例如启动Activity就不需要手动调用mMainThread.getInstrumentation.execStartActivity()函数了,降低了用户的使用成本,对外也屏蔽了具体的细节,保证了系统的易用性。

总结

外观模式是一个高频使用的设计模式,他的精髓就在于封装二字。

上一篇下一篇

猜你喜欢

热点阅读