An adapter can exploit an existing class to implement functionality in two ways. The adapter can use either composition or inheritance to access an existing class. If the adapter subclasses the existing class, it will inherit the methods and properties. If the adapter uses composition to access the existing class, the adapter class will hold a reference to an instance of the existing class, and use its methods and properties for implementation. In OOP, composition is generally preferred over inheritance. However, as we will see in subsequent examples, there are good arguments for both approaches depending on the context. Either way, the idea is to use the properties and methods of the existing class to provide most or some of the functionality required.
When the adapter uses composition to access the existing class, it's known as an object adapter. Object adapters store a reference to an instance of the existing class. Therefore, an object adapter uses an existing class.
All adapter classes implement an interface. In the class
diagram shown in Figure 5-2, the
ITarget declares a single
request(). The class diagram
shows that a reference to an instance of the
Adaptee class is stored in the variable
adaptee. When implementing the
request() method, the adapter references this instance.
Figure 5-2. Class diagram of an ...