You are on page 1of 3

Adapter Pattern Example

Consider a scenario in which there is an app thats developed in the US which returns the top
speed of luxury cars in miles per hour (MPH). Now we need to use the same app for our client in
the UK that wants the same results but in kilometers per hour (km/h).

To deal with this problem, well create an adapter which will convert the values and give us the
desired results:

Bridge Pattern Example

For the Bridge pattern, well consider two layers of abstraction; one is the geometric shape (like
triangle and square) which is filled with different colors (our second abstraction layer):

public interface Color { //standard constructors


void fill();
} abstract public String draw();
public class Blue implements Color { }
@Override public class Square extends Shape {
public String fill() {
return "Color is Blue"; public Square(Color color) {
} super(color);
} }
public abstract class Shape { public String draw() {
protected Color color; return "Square drawn. " + color.fill();
}
} assertEquals(square.draw(), "Square drawn.
public void Color is Red");
whenBridgePatternInvoked_thenConfigSuccess( }
){
//a square with red color Square drawn. Color: Red
Shape square = new Square(new Red()); Triangle drawn. Color: Blue

abstract class Vehicle { public Bike(Workshop workShop1, Workshop


protected Workshop workShop1; workShop2) {
protected Workshop workShop2; super(workShop1, workShop2);
protected Vehicle(Workshop workShop1, }
Workshop workShop2) { public void manufacture() {
this.workShop1 = workShop1; System.out.print("Bike ");
this.workShop2 = workShop2; workShop1.work();
} workShop2.work();
abstract public void manufacture(); }
} }
/** /**
* Refine abstraction 1 in bridge pattern * Implementor for bridge pattern
*/ * */
public class Car extends Vehicle { public interface Workshop {
public Car(Workshop workShop1, Workshop abstract public void work();
workShop2) { }
super(workShop1, workShop2); /**
} * Concrete implementation 1 for bridge pattern
@Override * */
public void manufacture() { public class Produce implements Workshop {
System.out.print("Car "); @Override
workShop1.work(); public void work() {
workShop2.work(); System.out.print("Produced");
} }
} }
/** /**
* Refine abstraction 2 in bridge pattern * Concrete implementation 2 for bridge pattern
*/ * */
public class Bike extends Vehicle { public class Assemble implements Workshop {
@Override
public void work() {
System.out.println(" Assembled.");
}
}
/*
* Demonstration of bridge design pattern
*/
public class BridgePattern {
public static void main(String[] args) {
Vehicle vehicle1 = new Car(new Produce(),
new Assemble());
vehicle1.manufacture();
Vehicle vehicle2 = new Bike(new Produce(),
new Assemble());
vehicle2.manufacture();
}
}

You might also like