IntentProvide a clean, robust, mechanism for controlling the relationship between two objects.
MotivationConnection style relationships between pairs of objects are common in games: A player flying a plane, an enemy npc equipping a weapon, or even particles generating from a smoke stack, and so on. By introducing a "relationship object" that exists for the lifetime of the relationship you can provide any methods needed for control over the relationship all in one easy to find place. The relationship object in the first example above might expose an interface for controlling the plane's physical inputs: ailerons, etc. in a simplified manner: perhaps, for instance, just a: SetDesiredRoll()
BenefitsHelps to reduce complexity of object code by keeping relationship management out of the main object hierarchies. Specifically it provides:
- Clear separation between each object's encapsulated interface and the interface that *only* exists when the two objects are connected to each other;
- Clear separation between different kinds of relationships between the same objects;
- Clear separation between different kinds of relationships for different kinds of objects.
- Facade: Overlaps this pattern somewhat in that they both can provide a simplified interface -- facade implies a permanent, architectural, relationship; whereas the R-Object provides an explicitly temporary interface that changes based on the particular objects involved.
- Adapter: Mechanism that takes user input ( via a game controller, mouse, keyboard, etc. ) and maps it onto the capabilities of the relationship object's interface.
- State: Lifts control over the relationship into classes based on behavior; helps sustain the relationship object by keeping the control over the relationship object itself out of the two classes involved in the relationship to a third-party.
LiabilitiesYou pay a tax in the form of additional classes and more distributed ownership of responsibility. Its also worth noting that the relationship object itself requires its own memory allocations. The additional class complexity ( again: in exchanged for reduced interface complexity ) may not be necessary in some cases, especially where:
- the control mechanism remains invariant through the course of the development cycle
- the r-object only handles concrete or "leaf" classes of the objects involved in the relationship
- one of the objects in the relationship only exists as long as the relationship exists
- the interface for the relationship is small and easily understood.