Context/Virtual Self

Published June 19, 2001 by Mat Noguchi, posted by Myopic Rhino
Do you see issues with this article? Let us know.
Advertisement
[size="5"]Intent

Sharing state data between multiple objects, either to implement a finite state machine or to compose multiple objects to perform a particular task.


[size="5"]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.


[size="5"]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.


[size="5"]Structure

See the State Pattern in Design Patterns for an implementation of the Context pattern.


[size="5"]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.
    [size="5"]Related Patterns

    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.
Cancel Save
0 Likes 0 Comments

Comments

Nobody has left a comment. You can be the first!
You must log in to join the conversation.
Don't have a GameDev.net account? Sign up!

Sharing state data between multiple objects, either to implement a finite state machine or to compose multiple objects to perform a particular task.

Advertisement
Advertisement
Advertisement