adapter - Harsh4999/Design-Patterns GitHub Wiki
Adapter
##Use
- We have an existing object which provides the functionality that client needs, but client code cant use this object because it expects an object with different interface
- Using adapter design pattern we make this existing object work with client by adapting the object to clients expected interface
- Its also called as Wrapper
- It has 2 variations 1) Class adapter 2) Object adapter
##UML
-
Class Adapter
- Adaptee = Its the class which provides the functionality which is needed by the client
- Target interface = Client is expecting an object which implements target interface however the Adaptee is not implementing Target interface
- Adapter = Its a class which extends from our existing Adaptee and it implements the Target interface we simply forward the call of interface method to Adaptee class method under the hood
- Client = Needs a function of Target interface which is doing the same thing in Adaptee class but doesnt want Adaptee class so we make a middlement which implements Target and extends Adaptee and under the hood forwards the interface method call to Adaptee class method call
-
Object Adapter (Prefered)
- Adaptee = Its existing class which provides the functionality
- Target interface = Its the interace wanted by client
- Object adapter = Here we implement the target interface but instead of extending Adaptee we make an object of adaptee inside it and than use it using composistion instead of inheritance
##Implementation
- Adapter class must implement target interface
- We will simply forward the method call from interface to the adaptee class
- In object adapter only change will be that instead of extending adaptee class we will accept adaptee as contructor args and make use of composition
- If we initiate adaptee directly in object adapter it will become tightly coupled thus we should always accept it as an argument
- We just need make sure sync between target interface and adaptee
- Object adapter allows to change adaptee easily
- Eg: InputStreamReader they adapt stream to reader interface
- It uses object composition