More C++ Idioms/Envelope Letter
From Wikibooks, the open-content textbooks collection
Contents |
[edit]
Envelope Letter
[edit] Intent
Supporting multiple implementations of a single abstract data type (ADT) instance across its lifetime
[edit] Motivation
When using Handle Body idiom and/or Counted Body idiom, quite often we come across situations where not only multiple implementations of an ADT share a common signature but also all the implementations (bodies) of a given ADT share signature with the ADT's interface (handle). In such cases, adding a new operation to a handle/body pair causes redundant update to both classes. If we want to capture this relationship between handle and body interfaces, envelope/letter idiom is used.
[edit] Solution and Sample Code
Derive all body classes from a common base class. To reflect the commonality in signature between the handle and the body, use the handle class as the common base class for alternative bodies. Make handle member functions virtual. Each alternative implementation derived from the handle class (in its role as the class defining the interface to the implementations) overrides suitable virtual functions. The base class implementation of these member functions defines the handle class functionality: it forwards requests to its associated body class instance.
class RealNumber; class ComplexNumber; class Number { public: virtual Number multiply (Number const &); protected: Number * nptr; }; class ComplexNumber : public Number { public: virtual Number multiply (Number const & n) { // ... if (this becomes a RealNumber number after multiplication) { this->nptr = new RealNumber (...); // metamorphize // .... } // .... } }; class RealNumber : public Number { // ... };
The ADT instance can now "metamorphize" between different body classes at run time. For example, A ComplexNumber can change itself to a Realnumber if its imaginary part becomes zero after some mathematical operation. An advantage of such a dynamic change in type is often increased efficiency. Moreover, new signatures need be added in one less place than if the information were duplicated. This idiom is the basis for Virtual Constructor idiom. In Algebraic Hierarchy, this pattern forms the basis for a Promotion Ladder.
[edit] Known Uses
[edit] Related Idioms
[edit] References
- http://users.rcn.com/jcoplien/Patterns/C++Idioms/EuroPLoP98.html#EnvelopeLetter
- Advanced C++ Programming Styles and Idioms by James Coplien, Addison Wesley, 1992.
[edit] Copyright
Copyright ©1998 Lucent Technologies, Bell Labs Innovations. All rights reserved. Permission granted to reprint verbatim for non-commercial use provided this copyright notice appears.