70 likes | 139 Vues
The Adapter Pattern. Scenario : An Existing System (your client code) interfaces to a Vendor Class library you purchased and incorporated into an application your company is currently selling. Existing System. Vendor1 Class. Vendor1 interface.
E N D
The Adapter Pattern SE-2811 Dr. Mark L. Hornick
Scenario: An Existing System (your client code) interfaces to a Vendor Class library you purchased and incorporated into an application your company is currently selling Existing System Vendor1 Class Vendor1 interface The Vendor goes out of business; what do you do???
The original configuration The ClientApp is writtensuch that it is heavily dependenton the functionality implementedin ServiceProvider, and is loadedwith calls to various ServiceProvidermethods. ServiceProvider may implementnumerous methods in a real situation;not only the few methods shown here SE-2811 Dr. Mark L. Hornick
Adapter (Wrapper) Pattern Existing System Vendor2 Class • Adapter • Implements the interface your classes expect • And talks to the vendor interface to service your requests. Existing System Vendor2 Class Adapter
The Adapter configuration 2. An interface declaring the same methodsas the original ServiceProvider is created 3. A replacement classfor the original ServiceProvider is found that providessimilar functionality,but with a differentset of methods: the adaptee 4. An adapter class is writtenwhich maps calls from the original methods to the new methods 1. The original ServiceProvider class is obsolete and discarded
The Adapter Pattern features • The client makes a request to the adapter by calling a method on it by continuing to program to the interface that mimics the methods of the original class. • The adapter translates the request into one or more calls on the adaptee • The amount of code is usually small, but may be complex due to indirect mappings from the original methods to the new methods. • The adapter transforms data or results from the adaptee into the form expected by the client • The client receives the results of the call and doesn’t care that there is an adapter doing the translation. • The only change to the client is that it must create aninstance of the adapter rather than the original vendor class.
Cases to use Adapter • Legacy code exists that interfaces to a class library that has changed • Revision change • Vendor change • New application is being developed that will have to interface to a class library that has yet to be defined • Define an interface and write the adapter later SE-2811 Dr. Mark L. Hornick