Adapter Pattern

Use Adapter pattern when
– Adapting interfaces. You want to use an existing class, and its interface
does not match the one you need.
– Reusable in Future. You want to create a reusable class that
cooperates with unrelated or unforeseen classes, that is, classes that
don't necessarily have compatible interfaces.
– Object adapter only. 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.


public interface Adaptee {
public void drive();
}

public interface Target {
public void screw();
}

public class Socket implements Adaptee{
String type;
double size;
public Socket(String type, double size){
this.type = type;
this.size = size;
}
@Override
public void drive() {
System.out.println("instance of Adaptee");
System.out.println("Socket screw with "+ type+"size " +size +"\n");
}
}

public class Adapter implements Target{
Adaptee adaptee;
Adapter(Adaptee adaptee){
this.adaptee = adaptee;
}

@Override
public void screw() {
System.out.println("Adapter screw");
adaptee.drive();
}
}

public class Ratchet implements Target{
Adapter adapter;
String type;
double size;
public Ratchet(String type, double size, Adapter adapter){
this.type = type;
this.size = size;
this.adapter = adapter;
}

@Override
public void screw(){
System.out.println("instance of Target");
System.out.println("Ratchet screw with "+ type+"size " +size);
adapter.screw();
}
}

public class Main {

public static void main(String[] args) {
Adaptee socket = new Socket("female", 0.25);
Adapter adapter = new Adapter(socket);
Ratchet ratchet = new Ratchet("male", 0.5, adapter);
socket.drive();
adapter.screw();
ratchet.screw();
}
}