What is the purpose of ContextWrapper (having a proxy for Context)?

问题: 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.

  • 发表于 2019-03-26 05:56
  • 阅读 ( 182 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除