adapter Flashcards
the adapter pattern is defined as
allowing incompatible classes to work together by converting the interface of one class into another expected by the clients
The class diagram of the adapter pattern consists of the following entities
Target
Client
Adaptee
Adapter
We’ll need an adapter here that can make the HotAirBalloon class work with the IAircraft interface. The adapter in pattern-speak should
implement the client interface, which is the IAircraft interface.
The adapter implementation would be the following:
public class Adapter implements IAircraft {
HotAirBalloon hotAirBalloon;
public Adapter(HotAirBalloon hotAirBalloon) {
this.hotAirBalloon = hotAirBalloon;
}
@Override
public void fly() {
String feulUsed = hotAirBalloon.inflateWithGas();
hotAirBalloon.fly(feulUsed);
}
}
The important things to note about the adapter are:
The adapter is composed with the Adaptee object, which in our case is the HotAirBalloon object.
The adapter implements the interface the client knows about and consumes. In this case, it is the IAircraft.
Note the client is manipulating objects that implement the IAircraft interface. It doesn’t know anything about the HotAirBalloon class and the adapter is responsible for masking the gory details for the client.. Let’s see the client code now
public void main() {
HotAirBalloon hotAirBalloon = new HotAirBalloon(); Adapter hotAirBalloonAdapter = new Adapter(hotAirBalloon); hotAirBalloonAdapter.fly(); }
Using objects for adaptation gains us the usual benefits of object composition,
The design becomes flexible and the adapter can stand in place of the adaptee or any of its subclassed-objects.
The class adapter works via multiple inheritance, the idea is that
the adapter extends both, the interface in use by the client, as well as, the adaptee class. Adaptation works via inheritance instead of composition.
In the Java API, one can find as examples of the adapter pattern
java.io.InputStreamReader and java.io.OutputStreamWriter