Shape.java
public abstract class Shape {
protected ColorAPI colorHandle;
public Shape(ColorAPI colorHandle){
this.colorHandle=colorHandle;
}
public abstract void draw();
}
ColorAPI.java
public interface ColorAPI {
public void applyColor();
}
Square.java
public class Square extends Shape {
private int x,y;
public Square(int x, int y, ColorAPI colorHandler) {
// TODO Auto-generated constructor stub
super(colorHandler);
this.x=x;
this.y=y;
}
@Override
public void draw() {
// TODO Auto-generated method stub
System.out.println("Drawing shape of square from co-ordinates x:" + this.x + ", y:"+this.y);
this.colorHandle.applyColor();
}
}
GreenColor.java
public class GreenColor implements ColorAPI {
public GreenColor() {
// TODO Auto-generated constructor stub
super();
}
@Override
public void applyColor() {
// TODO Auto-generated method stub
System.out.println("applying green color");
}
}
RedColor.java
public class RedColor implements ColorAPI {
public RedColor() {
// TODO Auto-generated constructor stub
}
@Override
public void applyColor() {
// TODO Auto-generated method stub
System.out.println("Applying red color");
}
}
BridgePatternDemo.java
public class BridgePatternDemo {
public BridgePatternDemo() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
// TODO Auto-generated method stub
//Draw the Red square
ColorAPI colorHandleRed = new RedColor();
Shape redSquare = new Square(10, 10, colorHandleRed);
redSquare.draw();
//Draw the Green Square
ColorAPI colorHandleGreen = new GreenColor();
Shape greenSquare = new Square(20, 20, colorHandleGreen);
greenSquare.draw();
}
}
Output
