Skip to content

Commit afe5d24

Browse files
committed
Added adapter pattern and its test case
1 parent 7e33042 commit afe5d24

File tree

5 files changed

+66
-0
lines changed

5 files changed

+66
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package src.main.java.com.designpatterns.structural.adapter;
2+
3+
public class BugattiVeyron implements Movable {
4+
@Override
5+
public double getSpeed() {
6+
return 268;
7+
}
8+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
package src.main.java.com.designpatterns.structural.adapter;
2+
3+
public interface Movable {
4+
// Returns the speed of the movable in MPH
5+
double getSpeed();
6+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package src.main.java.com.designpatterns.structural.adapter;
2+
3+
/**
4+
* An Adapter pattern acts as a connector between two incompatible interfaces that otherwise cannot be connected
5+
* directly. An Adapter wraps an existing class with a new interface so that it becomes compatible with the client’s
6+
* interface.
7+
* <br>
8+
* The main motive behind using this pattern is to convert an existing interface into another interface that the client
9+
* expects. It’s usually implemented once the application is designed.
10+
*
11+
* @see <a href="https://en.wikipedia.org/wiki/Adapter_pattern">Adapter Pattern</a>
12+
*/
13+
public interface MovableAdapter {
14+
// Returns the speed of the movable in KPH
15+
double getSpeed();
16+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package src.main.java.com.designpatterns.structural.adapter;
2+
3+
public class MovableAdapterImpl implements MovableAdapter {
4+
private Movable luxuryCars;
5+
6+
public MovableAdapterImpl(Movable luxuryCars) {
7+
this.luxuryCars = luxuryCars;
8+
}
9+
10+
@Override
11+
public double getSpeed() {
12+
return convertMPHtoKMPH(luxuryCars.getSpeed());
13+
}
14+
15+
private double convertMPHtoKMPH(double mph) {
16+
return mph * 1.60934;
17+
}
18+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package src.test.java.com.designpatterns.structural;
2+
3+
import org.junit.Test;
4+
import src.main.java.com.designpatterns.structural.adapter.BugattiVeyron;
5+
import src.main.java.com.designpatterns.structural.adapter.Movable;
6+
import src.main.java.com.designpatterns.structural.adapter.MovableAdapter;
7+
import src.main.java.com.designpatterns.structural.adapter.MovableAdapterImpl;
8+
9+
import static org.junit.Assert.assertEquals;
10+
11+
public class MovableAdapterTest {
12+
@Test
13+
public void testMovableAdapter() {
14+
Movable bugattiVeyron = new BugattiVeyron();
15+
MovableAdapter bugattiVeyronAdapter = new MovableAdapterImpl(bugattiVeyron);
16+
assertEquals(bugattiVeyronAdapter.getSpeed(), 431.30312, 0.00001);
17+
}
18+
}

0 commit comments

Comments
 (0)