Context Object

A context object encapsulates the references/pointers to services and configuration information used/needed by other objects. It allows the objects living within a context to see the outside world. Objects living in a different context see a different view of the outside world.

If you need to use a mail service, for example, where does it come from? You can imagine using a singleton, a global variable, a registration mechanism, a context object, creating a new service for every user. Any others?

Each approach has their own advantages and disadvantages.


Moved from SingletonPattern

So are there any patterns for avoiding singletons then?

Check out the MonostatePattern in C++; make all the data members static. I haven't used it at work but I know a guy who swears by it -- BillWeston

If I have a bunch of these 'there should be only one of these' type objects I generally throw them on a palette or workbench that gets passed around. Instead of passing a bunch of parameters in to classes I can just pass the Palette or Workbench. This also lets folks that are maintaining the code know my intention. -- FrankMcGeough


An alternative to passing a palette/workbench around (which couples the whole system to the palette) is to have a singleton Registry from which you obtain all the other singletons. Yes, the registry is a global variable but it's the only one (within that layer/subsystem) and all the things you get from the registry can just be normal easily-tested classes. Ensuring proper usage is just a matter of making sure that no-one ever calls the constructors of these classes but instead use the registry.


Note that this alternative to raw singletons is also known as RegistryPattern (in Fowler's PatternsOfEnterpriseApplicationArchitecture) and even mentioned in passing in the GoF book itself.


See ContextObjectsAreEvil, ExplicitManagementOfImplicitContext, PowerBox


CategoryContext


EditText of this page (last edited November 20, 2014) or FindPage with title or text search