Sharing state data between multiple objects, either to implement a finite state machine or to compose multiple objects to perform a particular task. Problem
Sharing data between multiple objects that have only one instance is pretty easy. Global data or singletons are easy solutions. However, if you want to compose discrete objects into a single component, any sort of global access pattern fails to scale to a finer level. Solution
Create an object Context that will hold any state data and methods relevant to the operation of the component. Add this object as a parameter or member pointer to every class the component will create and use. Have the component create and own the Context object. Using Context as an extra parameter provides more flexibility with respect to usage, as it allows multiple components to rely on a single object for part of their implementation. Structure
See the State Pattern in Design Patterns
for an implementation of the Context pattern. Consequences
- Easier development of components that are a composition of smaller objects.
- Extra overhead, either as an extra parameter to every method call or an extra member pointer.
- Using the Context object as an extra parameter allows stateless objects (i.e. the Context object contains all relevant state information) to be implemented as Flyweights, obviating the need for multiple instances of lightweight objects.
State uses a Context to pass state information between various states. Context can be thought of as a Singleton with finer levels of access beyond global.