0% found this document useful (0 votes)
31 views

Bridge Design Pattern - Exp4

Uploaded by

Suresh Naidu
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Bridge Design Pattern - Exp4

Uploaded by

Suresh Naidu
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Bridge Design Pattern

The bridge design pattern is a type of structural design pattern which is used to
split a large class into two separate inheritance hierarchies (a collection of 'is-
a' relationships); one for the implementations and one for the abstractions.
These hierarchies are then connected to each other via object composition,
forming a bridge-like structure. This pattern is also known as the Handle-Body
Design Pattern.

When Will We Need Bridge Design Pattern?


Whenever we use Inheritance, our implementations (child classes) and the abstractions
(parent classes) are generally coupled (dependent) on each other. This is because the
implementations implement or extend the abstractions depending upon whether the
abstraction is an abstract class or an interface. In these cases, we can use the Bridge Design
Pattern to decouple this dependency.

UML Diagram:
Source Code:

// Java code to demonstrate bridge design pattern

// abstraction in bridge pattern

abstract class Vehicle {

protected Workshop workShop1;

protected Workshop workShop2;

protected Vehicle(Workshop workShop1, Workshop workShop2)

this.workShop1 = workShop1;

this.workShop2 = workShop2;

abstract public void manufacture();

// Refine abstraction 1 in bridge pattern

class Car extends Vehicle {

public Car(Workshop workShop1, Workshop workShop2)

super(workShop1, workShop2);

@Override

public void manufacture()

System.out.print("Car ");

workShop1.work();

workShop2.work();

}
}

// Refine abstraction 2 in bridge pattern

class Bike extends Vehicle {

public Bike(Workshop workShop1, Workshop workShop2)

super(workShop1, workShop2);

@Override

public void manufacture()

System.out.print("Bike ");

workShop1.work();

workShop2.work();

// Implementer for bridge pattern

interface Workshop

abstract public void work();

// Concrete implementation 1 for bridge pattern

class Produce implements Workshop {

@Override

public void work()

System.out.print("Produced");

}
}

// Concrete implementation 2 for bridge pattern

class Assemble implements Workshop {

@Override

public void work()

System.out.print(" And");

System.out.println(" Assembled.");

// Demonstration of bridge design pattern

class Main {

public static void main(String[] args)

Vehicle vehicle1 = new Car(new Produce(), new Assemble());

vehicle1.manufacture();

Vehicle vehicle2 = new Bike(new Produce(), new Assemble());

vehicle2.manufacture();

You might also like