Skip to content

Latest commit

 

History

History
54 lines (48 loc) · 1.21 KB

adapter.md

File metadata and controls

54 lines (48 loc) · 1.21 KB

Singleton

Description

Allowing objects with incompatible interfaces to collaborate

Diagram

Code

Check code here

public interface Movable {
    double getSpeed();// speed in MPH
}
public class Car implements Movable {
    @Override
    public double getSpeed() {
        return 150;
    }
}
public class Boat implements Movable {
    @Override
    public double getSpeed() {
        return 300;
    }
}
public interface MovableAdapter {
    double getSpeed(); // speed in KM/H
}
public class MovableAdapterImpl implements MovableAdapter {
    private Movable movable;
    public MovableAdapterImpl(Movable movable) {
        this.movable = movable;
    }
    @Override
    public double getSpeed() {
        return movable.getSpeed() * 1.60934;
    }
}

To access the instance

Movable bugatti = new Car(268);
final double speedInMPH = bugatti.getSpeed();
MovableAdapter bugattiVAdapter = new MovableAdapterImpl(bugatti);
final double speedInKMH = bugattiVAdapter.getSpeed();

Use cases

  • whenever you want to use an existing class, but it's interface isn't compatible with the rest of the code