Definition
- Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.
UML Class Diagram
Adapter: when and where use it
- .NET developers write classes that expose methods that are called by clients. Most of the time they will be able to control the interfaces, but there are situations, for example, when using 3rd party libraries, where they may not be able to do so.
- The 3rd party library performs the desired services but the interface methods and property names are different from what the client expects. This is a scenario where you would use the
Adapter pattern. The Adapter provides an interface the client expects using the services of a class with a different interface. Adapters are commonly used in programming environments where new components or new applications need to be integrated and work together with existing programming components.
- Adapters are also useful in refactoring scenarios. Say, you have two classes that perform similar functions but have different interfaces. The client uses both classes, but the code would be far cleaner and simpler to understand if they would share the same interface.
- You cannot alter the interface, but you can shield the differences by using an Adapter which allows the client to communicate via a common interface. The Adapter handles the mapping between the shared interface and the original interfaces.
Sample
- Target class (the expected class client want to get)
- Adapter class (return class from services or server)
- Adaptee class (converter class - convert from a class to an expected class)
- Client class
(Ref: Gang of Four tutorial)
No comments:
Post a Comment