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


Industrial Training

We offers Placement Oriented Training on Java, Spring, JSF, Hibernate, PHP, AngularJS, Angular 4, PLSQL, Oracle BI Publisher etc. We also provides Online training, please mail us at hr@codesjava.com.

Development

We also provides the Development services for Website Development , Java Development, PHP Development, Android App Development etc. You can contact us on hr@codesjava.com.

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