Jump to content

  • Log In with Google      Sign In   
  • Create Account

Like
0Likes
Dislike

Context/Virtual Self

By Mat Noguchi | Published Jun 19 2001 05:39 PM in General Programming

context objects state object extra multiple data parameter component
If you find this article contains errors or problems rendering it unreadable (missing images or files, mangled code, improper text formatting, etc) please contact the editor so corrections can be made. Thank you for helping us improve this resource

Intent

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.
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.





Comments

Note: Please offer only positive, constructive comments - we are looking to promote a positive atmosphere where collaboration is valued above all else.




PARTNERS