Context/Virtual Self
IntentSharing state data between multiple objects, either to implement a finite state machine or to compose multiple objects to perform a particular task. ProblemSharing 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. SolutionCreate 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. StructureSee the State Pattern in Design Patterns for an implementation of the Context pattern. Consequences
Related PatternsState 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. Discuss this article in the forums
See Also: © 1999-2011 Gamedev.net. All rights reserved. Terms of Use Privacy Policy
|