美文网首页
外观模式

外观模式

作者: 1dot4 | 来源:发表于2019-02-20 19:02 被阅读0次

    介绍

    外观模式在开发过程中的运用频率非常高,尤其是第三方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()函数了,降低了用户的使用成本,对外也屏蔽了具体的细节,保证了系统的易用性。

    总结

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

    相关文章

      网友评论

          本文标题:外观模式

          本文链接:https://www.haomeiwen.com/subject/aqghyqtx.html