Java bridge design pattern

Java bridge design pattern comes under structural design patterns and it is used to decouple an abstraction from its implementation so that the two can vary independently. It uses composition approach over inheritance.

Example

Color.java

package com.w3schools;
 
public interface Color {
	public void fillColor();
}

GreenColor.java

package com.w3schools;
 
public class GreenColor implements Color {
	@Override
	public void fillColor() {
		System.out.println("green");		
	}
}

BlueColor.java

package com.w3schools;
 
public class BlueColor implements Color {
	@Override
	public void fillColor() {
		System.out.println("blue");		
	}
}

Shape.java

package com.w3schools;
 
public abstract class Shape {	
	//Composition approach
	protected Color color;
 
	public Shape(Color color){
		this.color=color;
	}
 
	abstract public void fillColor();	
}

Circle.java

package com.w3schools;
 
public class Circle extends Shape {	
	public Circle(Color color) {
		super(color);
	}
 
	@Override
	public void fillColor() {
		System.out.print("Circle filled with color: ");
		color.fillColor();
	} 	
}

Rectangle.java

package com.w3schools;
 
public class Rectangle extends Shape {	
	public Rectangle(Color color) {
		super(color);
	}
 
	@Override
	public void fillColor() {
		System.out.print("Rectangle filled with color: ");
		color.fillColor();
	} 	
}

BridgePatternTest.java

package com.w3schools;
 
public class BridgePatternTest { 
   public static void main(String args[]){	   
	   Shape circle = new Circle(new BlueColor());
	   circle.fillColor();
 
	   Shape rectangle = new Rectangle(new GreenColor());
	   rectangle.fillColor();
   }
}

Output

Circle filled with color: blue
Rectangle filled with color: green