Callbacks in C++
dual purpose class (only if you have to)
problem:
You need a single class to fill one of two mutually exclusive roles
where the role is determined at the time of construction.
context:
- C++
- A single class must play one of two roles selected at construction
time.
- The two roles have slightly different sate requirements.
- You want the state of the object to fit in as small a space as possible.
- You have a really good reason why this class should not be split into
two separate classes.
forces:
- You want to fit the data into as small a space as possible.
- You want the class to be capable of two or more separate roles.
- The implementation should make it obvious what is needed for what role.
- You realize that having a single class fill two roles is usually the
wrong thing to do and so need a good reason for doing this.
solution:
- Since the class is filling two mutually different roles and since there
is slightly different state information, some of the state information
can be made to overlap by using an anonymous union.
- There is at least one constructor specific to each separate role.
forces resolved:
- The class will be as compact as it can and still be capable of filling
any one of two or more roles selected at the time data is placed in the
class.
- Separate constructors make it easier to determine what out of the class
is used for what role.
- The class will be capable of filling different roles with the role
selected at construction time.
- The last force, having a good reason for doing this, must be resolved
on a case by case basis. One reason might be that you want to pass this
class by value to the same object or function regardless of which role
the object is filling.
design rationale:
Unions are a classic C way of overloading functionality into a single
structure. Since C++ allows inheritance and polymorphism, most reasons
for why you would want to go this route instead of splitting the class
or structure into multiple classes or structures are eliminated. This pattern
is here more as a reminder that this technique should rarely be used. This
technique is most likely to be useful when creating an abstract data type
that must be implemented using a family of classes.
[View/Add Comments]
Callbacks in C++
Copyright © 1996-2000 Paul Jakubik
Created: 26 July 1996. Last update: 26 November 2000.
pauljakubik@yahoo.com