By: R.C. Martin
Published in: PLoPD1
Category: C++ Idioms
Summary: Patterns (most are C++ idioms) found in an application and a classification scheme.
Containers need to be iterated by clients that don't know the kind of container they are using. Arrange all containers into a common inheritance hierarchy that can be linearly iterated. Use Prototype [Gamma+95], Strategy [Gamma+95], and Factory Method [Gamma+95] to create a concrete class that can iterate over any container in the hierarchy.
Many containers have membership semantics. These containers can have set operations. Clients need to perform these operations without knowing the kind of container they are using. Create an inheritance and containment hierarchy for all containers that exhibit membership semantics.
FSMs are often implemented as a mixture of control and behavior, which makes them hard to understand. Even when behavior and control are separated, as in State [Gamma+95], it is difficult to derive new FSMs from old ones and difficult to override old behaviors or add new ones because of a cyclic dependency between behaviors and the control mechanisms. Use inheritance to break the dependency cycle.
Category: C++ Idioms, Finite State Machines
Servers need to send messages to their clients. This is difficult in C++ because the server must use an interface that is part of the client, making the server depend on the client. Instead, create abstract client interfaces that have the required interfaces and are inherited by the client.
Sometimes the same loop will appear over and over in different parts of the application. The loop will be similar, but the body will be different. If the looping structure changes once, it must be changed everywhere. Write the loop once. Use inheritance to implement different bodies.