"Hello, Amigo! Today I will tell you what exactly an «adapter» is. I hope that after learning about this topic you'll have a much better understanding of input/output streams."
Imagine your program uses two frameworks written by other programmers/companies. Both frameworks are very good and use OOP principles: abstraction, polymorphism, encapsulation. Together, they almost completely cover what your program needs to do. You're left with a simple task. You need to pass objects created by one framework to the other framework. But both frameworks are completely different and "don't know about each other", i.e. they don't have any classes in common. You need to somehow convert the objects of one framework into objects of the other.
This task can be beautifully solved by applying the «adapter» technique (design pattern):
Java code | Description |
---|---|
|
This reflects the adapter design pattern.
The basic idea is that the MyClass class converts (adapts) one interface to the other. |
"Can you give me a more specific example?"
"OK. Let's say that each framework has its own unique "list" interface. They might look something like this:"
Java code | Description |
---|---|
|
Code from the first (Alpha) framework
AlphaList is one of the interfaces that allows the framework code to interact with the code that uses the framework. |
|
AlphaListManager AlphaListManager is a class in the framework. Its createList method creates an AlphaList object |
|
Code from the second (Beta) framework.
BetaList is one of the interfaces that allows the framework code to interact with the code that uses the framework. BetaSaveManager is a class in the framework. Its saveList method saves a BetaList object |
|
«Adapter» class that converts from the AlphaList interface to the BetaList interface
The ListAdapter class implements the BetaList interface from the second framework. When someone calls these methods, the class code «forwards» the calls to the list variable, which is an AlphaList from the first framework. An AlphaList object is passed to the ListAdapter constructor The setSize method operates according to the following rules: if the size of the list must be increased, add empty (null) items. If the size of the list needs to be reduced, delete items at the end. |
|
An example of how it might be used |
"I liked your last example most of all. Very concise and understandable."
GO TO FULL VERSION