CodesJava

Easy learning with example program codes

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.codesjava;
 
public interface Color {
	public void fillColor();
}

GreenColor.java

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

BlueColor.java

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

Shape.java

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

Circle.java

package com.codesjava;
 
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.codesjava;
 
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.codesjava;
 
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
Sign Up/ Sign In
Ask a Question


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki