The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.designpattern.structuralpattern;
/**
*
* @author palash
*/
public class BridgePattern {
public static void main(String[] args){
// first example
Fan fan = new Fan();
fan.switchOn();
Bulb bulb = new Bulb();
bulb.switchOff();
// second example
Shape[] shapes = new Shape[]{
new CircleShape(1, 2, 3, new DrawingAPI1()),
new CircleShape(5, 7, 11, new DrawingAPI2()),
};
for(Shape shape : shapes){
shape.resizeByPercentage(2.5);
shape.draw();
}
}
}
// first example
interface Switch{
public void switchOn();
public void switchOff();
}
class Fan implements Switch{
@Override
public void switchOn() {
System.out.println("Fan's switch on");
}
@Override
public void switchOff() {
System.out.println("Fan's switch off");
}
}
class Bulb implements Switch{
@Override
public void switchOn() {
System.out.println("Bulb's switch on");
}
@Override
public void switchOff() {
System.out.println("Bulb's switch off");
}
}
///////////////////////////////////////
// second example
//implementor
interface DrawingAPI{
public void drawCircle(double x, double y, double radius);
}
// concreteImplementor
class DrawingAPI1 implements DrawingAPI{
@Override
public void drawCircle(double x, double y, double radius) {
System.out.printf("API1.circle at %f:%f radius %f\n", x, y, radius);
}
}
// concreteImplementor
class DrawingAPI2 implements DrawingAPI{
@Override
public void drawCircle(double x, double y, double radius) {
System.out.printf("API1.circle at %f:%f radius %f\n", x, y, radius);
}
}
// abstraction
abstract class Shape{
protected DrawingAPI drawingAPI;
protected Shape(DrawingAPI drawingAPI){
this.drawingAPI = drawingAPI;
}
public abstract void draw();
public abstract void resizeByPercentage(double pct);
}
class CircleShape extends Shape{
private double x,y,radius;
public CircleShape(double x, double y, double radius, DrawingAPI drawingAPI){
super(drawingAPI);
this.x = x; this.y = y; this.radius = radius;
}
@Override
public void draw() {
drawingAPI.drawCircle(x, y, radius);
}
@Override
public void resizeByPercentage(double pct) {
radius *= pct;
}
}