参考1
参考2
说明:Activity,Service,Application都是ContextWrapper的子类。ContextWrapper里面有一个Context类型的成员变量mBase,当然它实际的类型是ContextImpl。ContextWrapper实现方法的时候调用了mBase的方法。
继承关系图
装饰者模式类关系图
使用装饰者模式优势
(1)避免代码重复,将一些通用的方法如starActivity()放到ContextImpl中,避免Activity,Application,Service中重复代码。
(2)版本兼容,比如现在starActivity()等具有两种不同的实现。可以根据传入的具体类进行调用。比如增加一个ContextImplA,思考传统的类的实现方式和修饰者模式
类对比:
public class ContextWrapper extends Context {
Context mBase;
public ContextWrapper(Context base) {
mBase = base;
}
/**
* Set the base context for this ContextWrapper. All calls will then be
* delegated to the base context. Throws
* IllegalStateException if a base context has already been set.
*
* @param base The new base context for this wrapper.
*/
protected void attachBaseContext(Context base) {
if (mBase != null) {
throw new IllegalStateException("Base context already set");
}
mBase = base;
}
/**
* @return the base context as set by the constructor or setBaseContext
*/
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();
}
@Override
public Looper getMainLooper() {
return mBase.getMainLooper();
}