Extension Object

Intent

Attach additional methods to a class. Whereas Decorator requires that the core class's interface remain fixed as successive "wrappers" are applied, Extension Objects allow the class's interface to grow incrementally and dynamically.

Implementation

An abstract Extension base class "hasa" pointer to its abstract Subject base class owner. Concrete Extension derived classes specify the behavior (i.e. interface) appropriate for their responsibilities, and, use the "owner" member to call-back to the correct Subject object when their service is requested.

Each concrete Subject derived class "hasa" pointer to one or more Extension classes that it is meaningful for it to support. It also has a "Extension* getExtension(char* type)" method that accepts the identifier for the desired Extension class, and returns a pointer to that class if it is supported, or NULL if it is not.

Finally, to access a Subject object's Extension object, the client: calls the getExtension method with the "type" of the desired Extension class, performs RTTI to test the type of the returned object, and if the result is not-NULL then the desired method is called on the returned object.

Discussion

The focus of the Extension Objects pattern is to engineer a class to support additional methods, or services. Clients that want to leverage an interface extension, query the object first to see if it supports the extension before attempting to use it.

Normally, a class is extended by subclassing and adding methods to the derived class. Extension Object provides extensibility without the subclassing.

Some of the trade-offs associated with the pattern are: clients of the extended object become more complex, and there is a temptation to lean on this technique to rationalize reactive fixing rather than commit oneself to proactive design.