美文网首页
浅谈安卓开发中context用到的装饰模式

浅谈安卓开发中context用到的装饰模式

作者: 邱穆 | 来源:发表于2020-10-16 08:26 被阅读0次

浅谈安卓开发中context用到的装饰模式

一、UML图

context.png

说明:Context类是最根部的抽象类,不实现具体的功能。Context类的具体实现实际上是在ContextImpl类,里面具体实现了startActivity()方法。Activity、Service都是继承自ContextWrapper,ContextWrapper持有ContextImpl的引用,是其余装饰类的基类。

二、代码及相关说明

2.1 Context接口


publicabstractclassContext{//抽象类
    publicabstractvoidstartActivity(@RequiresPermissionIntentintent);//抽象方法
//其他代码略
} 

Context实际上是个抽象类,里面定义了大量的抽象方法,其中就包含了startActivity()方法。伪代码中Context类仅包含基本的抽象方法,其余代码省略。

2.2 ContextImpl类

classContextImplextendsContext{

@Override
    publicvoidstartActivity(Intentintent) {
    warnIfCallingFromSystemProcess();
    startActivity(intent,null);
   }
@Override
    publicvoidstartActivity(Intentintent,Bundleoptions) {//
    warnIfCallingFromSystemProcess();
    if((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK)==0&&options!=null&&ActivityOptions.fromBundle(options).getLaunchTaskId()==-1) {
        thrownewAndroidRuntimeException("Calling startActivity() from outside of an Activity " + " context requires the FLAG_ACTIVITY_NEW_TASK flag." + " Is this really what you want?");
        }
    mMainThread.getInstrumentation().execStartActivity(getOuterContext(),mMainThread.getApplicationThread(),null,(Activity)null,intent,-1,options);
   }
//其他代码略
}

ContextImpl类实现了Context类的具体实现,其中就包括startActivity()方法。

2.3 ContextWrapper类

publicclassContextWrapperextendsContext{//Context包装类

    ContextmBase;//持有Context引用
    publicContextWrapper(Contextbase) {//这里的base实际上就是ContextImpl
        mBase=base;
    }
    @Override
    publicvoidstartActivity(Intentintent) {
        mBase.startActivity(intent);//调用ContextImpl的startActivity()方法
     }
//其他代码略
}

ContextWrapper类是装饰类的基类,持有Context引用。通常在Activity、Service里面调用startActivity()方法,实际上是调用他们的父类ContextWrapper里面的startActivity()方法。

三、总结

Context类充当了抽象组件的角色,ContextImpl类则是具体的组件,而ContextWrapper就是具体的装饰角色,通过扩展ContextWrapper增加不同的功能,就形成了Activity、Service等子类。

相关文章

网友评论

      本文标题:浅谈安卓开发中context用到的装饰模式

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