Example: Car Steering Adapter | 185
methods and properties to accomplish what it needs to do. TheITargetinterface
could declare methods that are needed in the new context, but have no relation to
the existing class.
Key OOP Concepts in the Adapter Pattern
Comparing the advantages and disadvantages of object and class adapters enables us
to clearly understand the merits ofcompositionversusinheritancein OO (object-
oriented) design.
Object and Class Adapters Compared
Choosing between object and class adapters depends on the context in which they
are used. Object adapters that use parameterized constructors are flexible because
theAdapteeobject is passed to them. This decouples theAdaptorandAdapteeclasses,
allowing instances of subclasses ofAdaptee class to be passed to the adapter.
For their part, class adapters generally have less code, resulting in quicker implemen-
tation. Because they subclass theAdaptee,they have anis-arelationship with the
Adapteeclass. TheAdapterclass is therefore the sameTypeas theAdaptee,and easier
to deal with from a client standpoint. Clients need to create only one instance of the
Adapterclass (as opposed to both anAdapteeandAdapterinstance, in the case of
parameterized object adapters). Class adapters can also be less time-consuming to
implement if the target interface is large, because most methods will be inherited.
The decision to choose either an object or adapter class to implement an adapter
depends on many factors: flexibility required, the size of the interface, ease of imple-
mentation, and match between the required interface and theAdaptee.
As a general rule,compositionis better thaninheritancebecause of its flexibility and
loose coupling. However, the adapter pattern shows that there can be instances
where you can save time and gain coding efficiency by usinginheritance.
Example: Car Steering Adapter
Adapter patterns are commonly used when there is an existing legacy class that pro-
vides the functionality you require, but whose interface doesn’t conform to what you
need. Let’s assume that we have a legacy class calledLegacyCar, which is a car sprite
from an old game. TheLegacyCarclass was initially developed for use with a steering
wheel input device to provide an authentic driving experience. We will change the
interface to theLegacyCarclass so that we can steer the car using different input
devices such as a keyboard and mouse.