问题:
According to the Android documentation, ContextWrapper is a "[p]roxying implementation of Context that simply delegates all of its calls to another Context. Can be subclass...
可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
According to the Android documentation, ContextWrapper is a "[p]roxying implementation of Context
that simply delegates all of its calls to another Context
. Can be subclassed to modify behavior without changing the original Context
."
I don't have much experience with the proxy pattern. How is it used here and for what purpose? In other words, why don't its indirect subclasses, such as Activity and Service, directly subclass it?
回答1:
TO be able to override some of its behavior. For example, you would have a base Context for the app, then put it in a ContextWrapper and override the Resource object to theme it (which is what Android actually does).
As for why you'd do this rather than just subclass- so as not to have to make two, possibly very heavyweight objects. You could also share variables between the two, but that increases the possibility of memory leaks. Its also possible that creation of the object is expensive, but if its already done you can avoid that by proxying.