#590 Add explanation for Adapter

This commit is contained in:
Ilkka Seppälä 2017-08-19 10:00:18 +03:00
parent f47dc1eb7c
commit fbf5ffe67a
11 changed files with 121 additions and 176 deletions

View File

@ -19,10 +19,85 @@ Convert the interface of a class into another interface the clients
expect. Adapter lets classes work together that couldn't otherwise because of
incompatible interfaces.
![alt text](./etc/adapter.png "Adapter")
## Explanation
## General usage of Adapter Pattern:
+ Wrappers used to adopt 3rd parties libraries and frameworks - most of the applications using third party libraries use adapters as a middle layer between the application and the 3rd party library to decouple the application from the library. If another library has to be used only an adapter for the new library is required without having to change the application code.
Real world example
> Consider that you have some pictures in your memory card and you need to transfer them to your computer. In order to transfer them you need some kind of adapter that is compatible with your computer ports so that you can attach memory card to your computer. In this case card reader is an adapter.
> Another example would be the famous power adapter; a three legged plug can't be connected to a two pronged outlet, it needs to use a power adapter that makes it compatible with the two pronged outlet.
> Yet another example would be a translator translating words spoken by one person to another
In plain words
> Adapter pattern lets you wrap an otherwise incompatible object in an adapter to make it compatible with another class.
Wikipedia says
> In software engineering, the adapter pattern is a software design pattern that allows the interface of an existing class to be used as another interface. It is often used to make existing classes work with others without modifying their source code.
**Programmatic Example**
Consider a captain that can only use rowing boats and cannot sail at all.
First we have interfaces `RowingBoat` and `FishingBoat`
```
public interface RowingBoat {
void row();
}
public class FishingBoat {
private static final Logger LOGGER = LoggerFactory.getLogger(FishingBoat.class);
public void sail() {
LOGGER.info("The fishing boat is sailing");
}
}
```
And captain expects an implementation of `RowingBoat` interface to be able to move
```
public class Captain implements RowingBoat {
private RowingBoat rowingBoat;
public Captain(RowingBoat rowingBoat) {
this.rowingBoat = rowingBoat;
}
@Override
public void row() {
rowingBoat.row();
}
}
```
Now let's say the pirates are coming and our captain needs to escape but there is only fishing boat available. We need to create an adapter that allows the captain to operate the fishing boat with his rowing boat skills.
```
public class FishingBoatAdapter implements RowingBoat {
private static final Logger LOGGER = LoggerFactory.getLogger(FishingBoatAdapter.class);
private FishingBoat boat;
public FishingBoatAdapter() {
boat = new FishingBoat();
}
@Override
public void row() {
boat.sail();
}
}
```
And now the `Captain` can use the `FishingBoat` to escape the pirates.
```
Captain captain = new Captain(new FishingBoatAdapter());
captain.row();
```
## Applicability
Use the Adapter pattern when
@ -30,6 +105,7 @@ Use the Adapter pattern when
* you want to use an existing class, and its interface does not match the one you need
* you want to create a reusable class that cooperates with unrelated or unforeseen classes, that is, classes that don't necessarily have compatible interfaces
* you need to use several existing subclasses, but it's impractical to adapt their interface by subclassing every one. An object adapter can adapt the interface of its parent class.
* most of the applications using third party libraries use adapters as a middle layer between the application and the 3rd party library to decouple the application from the library. If another library has to be used only an adapter for the new library is required without having to change the application code.
## Consequences:
Class and object adapters have different trade-offs. A class adapter

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

View File

@ -1,70 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<class-diagram version="1.1.9" icons="true" always-add-relationships="false" generalizations="true" realizations="true"
associations="true" dependencies="false" nesting-relationships="true" router="FAN">
<class id="1" language="java" name="com.iluwatar.adapter.FishingBoat" project="adapter"
file="/adapter/src/main/java/com/iluwatar/adapter/FishingBoat.java" binary="false" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="656" y="355"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<class id="2" language="java" name="com.iluwatar.adapter.Captain" project="adapter"
file="/adapter/src/main/java/com/iluwatar/adapter/Captain.java" binary="false" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="228" y="185"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<class id="3" language="java" name="com.iluwatar.adapter.BattleFishingBoat" project="adapter"
file="/adapter/src/main/java/com/iluwatar/adapter/BattleFishingBoat.java" binary="false" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="463" y="357"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<interface id="4" language="java" name="com.iluwatar.adapter.BattleShip" project="adapter"
file="/adapter/src/main/java/com/iluwatar/adapter/BattleShip.java" binary="false" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="466" y="170"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</interface>
<realization id="5">
<end type="SOURCE" refId="2"/>
<end type="TARGET" refId="4"/>
</realization>
<association id="6">
<end type="SOURCE" refId="3" navigable="false">
<attribute id="7" name="boat"/>
<multiplicity id="8" minimum="0" maximum="1"/>
</end>
<end type="TARGET" refId="1" navigable="true"/>
<display labels="true" multiplicity="true"/>
</association>
<realization id="9">
<end type="SOURCE" refId="3"/>
<end type="TARGET" refId="4"/>
</realization>
<association id="10">
<end type="SOURCE" refId="2" navigable="false">
<attribute id="11" name="battleship"/>
<multiplicity id="12" minimum="0" maximum="1"/>
</end>
<end type="TARGET" refId="4" navigable="true"/>
<display labels="true" multiplicity="true"/>
</association>
<classifier-display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</classifier-display>
<association-display labels="true" multiplicity="true"/>
</class-diagram>

View File

@ -1,37 +0,0 @@
@startuml
package com.iluwatar.adapter {
class App {
+ App()
+ main(args : String[]) {static}
}
class BattleFishingBoat {
- LOGGER : Logger {static}
- boat : FishingBoat
+ BattleFishingBoat()
+ fire()
+ move()
}
interface BattleShip {
+ fire() {abstract}
+ move() {abstract}
}
class Captain {
- battleship : BattleShip
+ Captain()
+ Captain(battleship : BattleShip)
+ fire()
+ move()
+ setBattleship(battleship : BattleShip)
}
class FishingBoat {
- LOGGER : Logger {static}
+ FishingBoat()
+ fish()
+ sail()
}
}
BattleFishingBoat --> "-boat" FishingBoat
Captain --> "-battleship" BattleShip
BattleFishingBoat ..|> BattleShip
Captain ..|> BattleShip
@enduml

View File

@ -34,14 +34,14 @@ package com.iluwatar.adapter;
* object. This example uses the object adapter approach.
*
* <p>
* The Adapter ({@link BattleFishingBoat}) converts the interface of the adaptee class (
* {@link FishingBoat}) into a suitable one expected by the client ( {@link BattleShip} ).
* The Adapter ({@link FishingBoatAdapter}) converts the interface of the adaptee class (
* {@link FishingBoat}) into a suitable one expected by the client ( {@link RowingBoat} ).
*
* <p>
* The story of this implementation is this. <br>
* Pirates are coming! we need a {@link BattleShip} to fight! We have a {@link FishingBoat} and our
* Pirates are coming! we need a {@link RowingBoat} to flee! We have a {@link FishingBoat} and our
* captain. We have no time to make up a new ship! we need to reuse this {@link FishingBoat}. The
* captain needs a battleship which can fire and move. The spec is in {@link BattleShip}. We will
* captain needs a rowing boat which he can operate. The spec is in {@link RowingBoat}. We will
* use the Adapter pattern to reuse {@link FishingBoat}.
*
*/
@ -53,8 +53,8 @@ public class App {
* @param args command line args
*/
public static void main(String[] args) {
Captain captain = new Captain(new BattleFishingBoat());
captain.move();
captain.fire();
// The captain can only operate rowing boats but with adapter he is able to use fishing boats as well
Captain captain = new Captain(new FishingBoatAdapter());
captain.row();
}
}

View File

@ -23,33 +23,26 @@
package com.iluwatar.adapter;
/**
* The Captain uses {@link BattleShip} to fight. <br>
* The Captain uses {@link RowingBoat} to sail. <br>
* This is the client in the pattern.
*/
public class Captain implements BattleShip {
public class Captain implements RowingBoat {
private BattleShip battleship;
private RowingBoat rowingBoat;
public Captain() {
public Captain() {}
public Captain(RowingBoat rowingBoat) {
this.rowingBoat = rowingBoat;
}
public Captain(BattleShip battleship) {
this.battleship = battleship;
}
public void setBattleship(BattleShip battleship) {
this.battleship = battleship;
public void setRowingBoat(RowingBoat rowingBoat) {
this.rowingBoat = rowingBoat;
}
@Override
public void fire() {
battleship.fire();
}
@Override
public void move() {
battleship.move();
public void row() {
rowingBoat.row();
}
}

View File

@ -27,7 +27,8 @@ import org.slf4j.LoggerFactory;
/**
*
* Device class (adaptee in the pattern). We want to reuse this class
* Device class (adaptee in the pattern). We want to reuse this class.
* Fishing boat moves by sailing.
*
*/
public class FishingBoat {
@ -35,11 +36,7 @@ public class FishingBoat {
private static final Logger LOGGER = LoggerFactory.getLogger(FishingBoat.class);
public void sail() {
LOGGER.info("The Boat is moving to that place");
}
public void fish() {
LOGGER.info("fishing ...");
LOGGER.info("The fishing boat is sailing");
}
}

View File

@ -27,30 +27,22 @@ import org.slf4j.LoggerFactory;
/**
*
* Adapter class. Adapts the interface of the device ({@link FishingBoat}) into {@link BattleShip}
* interface expected by the client ({@link Captain}). <br>
* In this case we added a new function fire to suit the interface. We are reusing the
* {@link FishingBoat} without changing itself. The Adapter class can just map the functions of the
* Adaptee or add, delete features of the Adaptee.
* Adapter class. Adapts the interface of the device ({@link FishingBoat}) into {@link RowingBoat}
* interface expected by the client ({@link Captain}).
*
*/
public class BattleFishingBoat implements BattleShip {
public class FishingBoatAdapter implements RowingBoat {
private static final Logger LOGGER = LoggerFactory.getLogger(BattleFishingBoat.class);
private static final Logger LOGGER = LoggerFactory.getLogger(FishingBoatAdapter.class);
private FishingBoat boat;
public BattleFishingBoat() {
public FishingBoatAdapter() {
boat = new FishingBoat();
}
@Override
public void fire() {
LOGGER.info("fire!");
}
@Override
public void move() {
public void row() {
boat.sail();
}
}

View File

@ -24,13 +24,11 @@ package com.iluwatar.adapter;
/**
* The interface expected by the client.<br>
* A Battleship can fire and move.
* A rowing boat is rowed to move.
*
*/
public interface BattleShip {
public interface RowingBoat {
void fire();
void move();
void row();
}

View File

@ -39,9 +39,9 @@ public class AdapterPatternTest {
private Map<String, Object> beans;
private static final String BATTLESHIP_BEAN = "engineer";
private static final String FISHING_BEAN = "fisher";
private static final String CAPTAIN_BEAN = "captain";
private static final String ROWING_BEAN = "captain";
/**
* This method runs before the test execution and sets the bean objects in the beans Map.
@ -50,34 +50,29 @@ public class AdapterPatternTest {
public void setup() {
beans = new HashMap<>();
BattleFishingBoat battleFishingBoat = spy(new BattleFishingBoat());
beans.put(BATTLESHIP_BEAN, battleFishingBoat);
FishingBoatAdapter fishingBoatAdapter = spy(new FishingBoatAdapter());
beans.put(FISHING_BEAN, fishingBoatAdapter);
Captain captain = new Captain();
captain.setBattleship((BattleFishingBoat) beans.get(BATTLESHIP_BEAN));
beans.put(CAPTAIN_BEAN, captain);
captain.setRowingBoat((FishingBoatAdapter) beans.get(FISHING_BEAN));
beans.put(ROWING_BEAN, captain);
}
/**
* This test asserts that when we use the move() method on a captain bean(client), it is
* internally calling move method on the battleship object. The Adapter ({@link BattleFishingBoat}
* This test asserts that when we use the row() method on a captain bean(client), it is
* internally calling sail method on the fishing boat object. The Adapter ({@link FishingBoatAdapter}
* ) converts the interface of the target class ( {@link FishingBoat}) into a suitable one
* expected by the client ({@link Captain} ).
*/
@Test
public void testAdapter() {
BattleShip captain = (BattleShip) beans.get(CAPTAIN_BEAN);
RowingBoat captain = (RowingBoat) beans.get(ROWING_BEAN);
// when captain moves
captain.move();
captain.row();
// the captain internally calls the battleship object to move
BattleShip battleship = (BattleShip) beans.get(BATTLESHIP_BEAN);
verify(battleship).move();
// same with above with firing
captain.fire();
verify(battleship).fire();
RowingBoat adapter = (RowingBoat) beans.get(FISHING_BEAN);
verify(adapter).row();
}
}

View File

@ -466,6 +466,7 @@
<param>abstract-factory</param>
<param>builder</param>
<param>prototype</param>
<param>adapter</param>
</skipForProjects>
</configuration>
</plugin>