標籤:android裝飾者模式 context
在閻宏博士的《JAVA與模式》一書中開頭是這樣描述裝飾(Decorator)模式的:
裝飾模式又名封裝(Wrapper)模式。裝飾模式以對用戶端透明的方式擴充項物件的功能,是繼承關係的一個替代方案。
裝飾模式的結構
裝飾模式以對客戶透明的方式動態地給一個對象附加上更多的責任。換言之,用戶端並不會覺得對象在裝飾前和裝飾後有什麼不同。裝飾模式可以在不使用創造更多子類的情況下,將對象的功能加以擴充。(上文來源於網路)
裝飾模式的類圖如下:
在裝飾模式中的角色有:
● 抽象構件(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);
.......<span style="white-space:pre"></span> }
........ }
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關聯起來。
未完待續,有不對的地方,請指正。
Android與設計模式——裝飾者(Decorator)模式