200 likes | 304 Views
Structural Design Pattern: CLASS ADAPTER. a.k.a. WRAPPER By Ed Kim. Context. You have discovered a legacy class that provides some or all of the functionality you need but lacks the right interface for a given domain
E N D
Structural Design Pattern:CLASS ADAPTER a.k.a. WRAPPER By Ed Kim
Context • You have discovered a legacy class that provides some or all of the functionality you need but lacks the right interface for a given domain • More generally, you would like to create a reusable class that allows classes having incompatible interfaces to work together • You may not have access to the source code to modify the interface(s) of the class(es) in question • Assuming the source code is accessible, tailoring the class’s interface to a specific application might still a bad idea (e.g., increased coupling, excessive dependencies, reduced modularity, etc.)
The Wrapper Class • Present a familiar interface to the client while exploiting the services of an existing class made incompatible by its own interface • Calls made to the wrapper interface are mapped to the interface of the adapted class for actual implementation • Allows otherwise incompatible classes to work together • Existing class source code can remain intact, promoting loose coupling and increased modularity while reducing superfluous dependencies
The Client • Suppose your client is a North American travel iron (NATravelIron). NATravelIron
The Expected Interface • Regardless of its physical location, NATravelIron expects to make use of a NEMA 5-15 socket (NEMA515Socket) in order to obtain electricity. NEMA515Socket
The Incompatible Interface… • Suppose further that NATravelIron will be traveling for an indefinite period of time with its owner to Italy – a country where only sockets of type CEE 7/16 (CEE716Socket) are to be found. • How, then, will NATravelIron continue to function properly abroad? Italy CEE716Socket
…The Coveted Functionality • Clearly, CEE716Socket provides the same power delivery services in Europe that NEMA515Socket would provide in North America (ignoring any voltage discrepancies for the sake of argument), but CEE716Socket simply lacks the appropriate interface that NATravelIron needs to obtain electricity and thus function properly.
The Solution • Introduce a North America to Europe travel adapter (NAEUTravelAdapter) that presents the familiar NEMA515Socket interface to NATravelIron while exploiting the CEE716Socket interface to deliver power. NAEUTravelAdapter
Closing Remarks • Other issues, which are beyond the scope of this presentation, do exist with respect to class adapter usage – kindly refer to your nearest pattern reference for this information