6.6 The Use of Multiple Inheritance in the Design of Mixins
An interesting use for multiple inheritance is in the creation of mixins, which are inheritance hierarchies that abstract out certain properties from the classes that exhibit them. Each class picks and chooses which of the properties its objects will possess. For example, we may have some objects that are copyable, fillable, editable, and fontable. Others may only be copyable and fillable; still others are only fontable, etc. The design for such a mixin might look like the model in Figure 6.7.
Figure 6.7. An example of mixins.
One problem with mixins is that they are very static due to their implementation via inheritance. What if text is rotatable only when it is contained within a frame object, but cannot exhibit this behavior outside of a frame object? What if lines can be copied only when they are in selected mode? For the implementation of behavior that depends on the state of an object, it is best to use containment with conditional testing on the state of the object at runtime. Object-oriented structures created in this manner are called compositional mixins. Our questions above imply that we want our design of lines and text to be as those shown in Figure 6.8. When a line is told to copy itself, it does not inherit this functionality from the CopyableObject class as it did in Figure 6.7. Instead, the Line class itself implements copy to check first the state of the Line object to see if the line is selected. It then makes sure that it contains the necessary CopyableObject. Only when all conditions are satisfied does the Line class send a copy message to the CopyableObject. The Text object is designed in a similar manner with respect to rotation. The trade-off between a traditional mixin and a compositional mixin revolves around ease of adding behavior versus flexibility. The traditional mixin maximizes ease of adding behavior but is not flexible, while the compositional mixin increases the effort of adding new behavior but is more flexible.
Figure 6.8. An example of a compositional mixin.