android 装饰着模式,Android与设计模式——装饰者(Decorator)模式

在阎宏博士的《JAVA与模式》一书中开头是这样描述装饰(Decorator)模式的:

装饰模式又名包装(Wrapper)模式。装饰模式以对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案。

装饰模式的结构

装饰模式以对客户透明的方式动态地给一个对象附加上更多的责任。换言之,客户端并不会觉得对象在装饰前和装饰后有什么不同。装饰模式可以在不使用创造更多子类的情况下,将对象的功能加以扩展。(上文来源于网络)

装饰模式的类图如下:

3bcd68dc74d16e7b5d5bc3331148b322.png

在装饰模式中的角色有:

●  抽象构件(Context)角色:给出一个抽象接口,以规范准备接收附加责任的对象。

●  具体构件(ContextImpl)角色:定义一个将要接收附加责任的类。

●  装饰(ContextWrapper)角色:持有一个构件(Component)对象的实例,并定义一个与抽象构件接口一致的接口。

●  具体装饰(Activity/Service/Application)角色:负责给构件对象“贴上”附加的责任。

ContextImpl是抽象类Context的具体实现,ContextWrapper及所有其子类对象持有的Context均是ContextImpl对象。以Activity的Context为例,Activity创建是在ActivityThread中,Activity创建时:

public final class ActivityThread {.......

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {

......

if (activity != null) {

Context appContext = createBaseContextForActivity(r, activity);

CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());

Configuration config = new Configuration(mCompatConfiguration);

if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "

+ r.activityInfo.name + " with config " + config);

activity.attach(appContext, this, getInstrumentation(), r.token,

r.ident, app, r.intent, r.activityInfo, title, r.parent,

r.embeddedID, r.lastNonConfigurationInstances, config);.......

}........

}private Context createBaseContextForActivity(ActivityClientRecord r,

final Activity activity) {

ContextImpl appContext = new ContextImpl();

appContext.init(r.packageInfo, r.token, this);

appContext.setOuterContext(activity);

// For debugging purposes, if the activity's package name contains the value of

// the "debug.use-second-display" system property as a substring, then show

// its content on a secondary display if there is one.

Context baseContext = appContext;

String pkgName = SystemProperties.get("debug.second-display.pkg");

if (pkgName != null && !pkgName.isEmpty()

&& r.packageInfo.mPackageName.contains(pkgName)) {

DisplayManagerGlobal dm = DisplayManagerGlobal.getInstance();

for (int displayId : dm.getDisplayIds()) {

if (displayId != Display.DEFAULT_DISPLAY) {

Display display = dm.getRealDisplay(displayId, r.token);

baseContext = appContext.createDisplayContext(display);

break;

}

}

}

return baseContext;

}

}

createBaseContextForActivity()方法返回ContextImpl对象后,通过activity.attach()将ContextImpl对象与Activity关联起来。

未完待续,有不对的地方,请指正。

原文:http://blog.csdn.net/canghai1129/article/details/41577901

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值