1

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?

Ellen Spertus
  • 6,576
  • 9
  • 50
  • 101
  • Small correction: `Service` and `Application` classes *do* directly subclass `ContextWrapper`. Only `Activity` is an indirect subclass of `ContextWrapper` (through `ContextThemeWrapper`). Edit: oof, just realized you were talking about `Context` and not `ContextWrapper` there. – M.Ed Jun 24 '22 at 14:32

1 Answers1

3

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.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127