Core Java

Java Bridge Design Pattern Example

1. Introduction

In this article, we would be talking about one of the many Java Design Patterns – The Bridge Design pattern. In a large scale Java application built for enterprises, at times it becomes difficult to manage and understand the code. With a varying profile of developers working on the same project, it is necessary that the code being developed is understandable by new developers that join the project. This is possible only when there are standards in place. These standards should be meant to structural or develop the code in a way that is already expected by the new developers. The Java community has hence specified several design patterns. In each pattern there are certain pre-defined coding standards and structures to be followed. These specific standards and the structures of code assist in development of a code that is organised and easily manageable. Moreover, it also ascertains that the code is organised in a predefined manner and thus it is easily understandable by any new developer joining the project.

In order to ensure that these coding structures are standardised, Java defines a large bunch of design patterns which revolve around the various aspects of coding like how we define a specific class, how we link the classes to use other, how we leverage the core features of Java like the inheritence and interfaces, the creation of objects and the management of object behaviour.

2. Java Design patterns

There are three primary groups of these design patterns which are briefly explained below.

2.1 Creational Pattern

This group of patterns provides five different design patterns that primarily focus on the logic of creation and destruction of objects while concealing the actual implementation of the objects. This basically defines the standards for abstraction. Thus, this pattern controls the object access for each module that exists in the application.

2.2 Structural Pattern

This group of patterns provides us with seven different patterns to help the developers organise the class structure so that the desired classes and features are exposed in a desired manner. Additionally, they offer solutions to problems like interfacing different types of objects, entities or applications. They also guide in solving the problems of separating abstract classes from the actual implementation. This is where bridge pattern basically belongs.

2.3 Behavioural Pattern

This pattern category is mainly associated with the way objects communicate with each other. This includes messaging queues, passing messages via connecting classes and others. There are nearly eleven such patterns to define the communication methodologies.

In this article, we would be discussing one of the structural design patterns – the Bridge design pattern. The article would explain the concept behind this pattern with a real-life example to help you gain an insight on how the design pattern have really helped make a better project code. The next section covers the pattern logically to explain each component of the Bridge design pattern to prepare you to understand the code that lies ahead.

3. Bridge Design Pattern

The Bridge configuration design enables you to isolate the abstraction from the implementation. It is a basic plan design.

There are 2 sections in Bridge configuration design :

  • Abstraction
  • Implementation

This is an outline system that embodies an implementation class within an interface class.

The bridge design enables the Abstraction and the Implementation to be created freely and the customer code can get to just the Abstraction part without being worried about the Implementation part.

The abstraction is an interface or dynamic class and the practitioner is additionally an interface or conceptual class.

The abstraction contains a reference to the practitioner. Offspring of the abstraction are alluded to as refined abstractions, and offspring of the practitioner are concrete practitioners. Since we can change the reference to the practitioner in the abstraction, we can change the abstraction’s practitioner at run-time. Changes to the practitioner don’t influence customer code.

It expands the free coupling between class abstraction and it’s implementation.

The figure below elaborates the concept:

Java Bridge Design Pattern
Bridge Design Pattern

Abstraction – center of the bridge configuration design and characterizes the core. Contains a reference to the implementer.

Refined Abstraction – Extends the abstraction takes the better detail one level underneath. Conceals the better components from implemetors.

Implementer – It characterizes the interface for implementation classes. This interface does not have to compare straightforwardly to abstraction interface and can be altogether different. Abstraction devil gives an implementation regarding activities given by Implementer interface.

Solid Implementation – Implements the above implementer by giving solid implementation.

4. Coding Bridge Pattern

Now that we have understood the Bridge pattern basics, let us develop the code to understand the bridge pattern. Unlike the other design patterns, it is a bit complex to understand bridge pattern. Let us develop all the relevant classes before we understand the code. The code will be explained after the classes have been created.

Vehicle.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
package com.javacodegeeks;
// abstraction in bridge pattern
abstract class Vehicle {
    protected Workshop w1;
    protected Workshop w2;
      
    protected Vehicle(Workshop w1, Workshop w2)
        {
            this.w1 = w1;
            this.w2 = w2;
        }
      
    abstract public void manufacture();
}

Workshop.java

1
2
3
4
5
6
7
package com.javacodegeeks;
//Implementor for bridge pattern
interface Workshop
{
 abstract public void work();
}

Produce.java

01
02
03
04
05
06
07
08
09
10
package com.javacodegeeks;
//Concrete implementation 1 for bridge pattern
class Produce implements Workshop {
 @Override public void work()
 {
     System.out.print("Producing vehicle");
 }
}

Assemble.java

01
02
03
04
05
06
07
08
09
10
11
package com.javacodegeeks;
//Concrete implementation 2 for bridge pattern
class Assemble implements Workshop {
 @Override public void work()
 {
     System.out.println("Assembing Vehicle.");
 }
}

Bike.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
package com.javacodegeeks;
import com.javacodegeeks.Vehicle;
//Refine abstraction 2 in bridge pattern
class Bike extends Vehicle {
public Bike(Workshop w1, Workshop w2)
 {
     super(w1, w2);
 }
 @Override public void manufacture()
 {
     System.out.print("Bike ");
     w1.work();
     w2.work();
 }
}

Car.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
package com.javacodegeeks;
// Refine abstraction 1 in bridge pattern
class Car extends Vehicle {
public Car(Workshop w1, Workshop w2)
    {
        super(w1, w2);
    }
  
    @Override public void manufacture()
    {
        System.out.print("Car ");
        w1.work();
        w2.work();
    }
  
}

So far, we have created all the classes that depict the Bridge pattern. Each sub-component has two different classes with similar code. Now, the next class that we would develop is the actual main class that utilises this pattern to perform action.

BridgePattern.java

01
02
03
04
05
06
07
08
09
10
11
12
package com.javacodegeeks;
//Demonstration of bridge design pattern
class BridgePattern {
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();
 }
}

This is the final code. On execution of the above code, you get the following output.

1
2
Assembling Vehicle
Building Vehicle

In the above code, we created two implementations of a bridge class. These implementors assist in doing the tasks that the bridge class was created for. Thus, they utilise the abstract class to further advance the code and provides specific functionalities to the caller class. Although the code is self-explanatory, we would try and understand the same using the below images. Let us look at the below images. These images explain how the implementation would have been in absence of bridge pattern and how it changed by implementing using the bridge design pattern.

Java Bridge Design Pattern - Without Bridge Design Pattern
Without Bridge Design Pattern

Notice in the above image that if the bridge pattern would not have been implemented, there would have been unnecessary duplication of the production and assembly classes. Now let us see how this was changed in a Bridge design pattern.

Java Bridge Design Pattern - With Bridge Design Pattern
With Bridge Design Pattern

As it can be seen clearly, there is a direct reduction of redundant code due to a bridge between Vehicle and Workshop. Thus, Bridge pattern helps in highly simplifying the code. Now that we have clearly understood what bridge pattern is all about, let us look at its advantages and feasibility of its use.

5. Advantages of bridge design pattern

  • Decoupling abstraction from implementation – Inheritance firmly couples an abstraction with an implementation at arrange time. Bridge example can be utilized to maintain a strategic distance from the official among abstraction and implementation and to choose the implementation at run time.
  • Decrease in the quantity of sub classes – Sometimes, utilizing unadulterated legacy will build the quantity of sub-classes.
  • Cleaner code and Reduction in executable size
  • Interface and implementation can be shifted freely – Maintaining two diverse class chains of importance for interface and implementation qualifies for differ one autonomous of the other.
  • Enhanced Extensibility – Abstraction and implementation can be broadened autonomously.
  • Inexactly coupled customer code – Abstraction isolates the customer code from the implementation. Along these lines, the implementation can be changed without influencing the customer code and the customer code require not be incorporated when the implementation changes.
  • It is utilized primarily to actualize stage freedom include.
  • It includes one more technique level redirection to accomplish the goal.
  • Distribute abstraction interface in a different legacy chain of importance, and put the implementation in its own legacy order.
  • Utilize bridge example to run-time official of the implementation.
  • Utilize bridge example to delineate class chains of importance
  • Bridge is planned in advance to give the abstraction and the implementation a chance to differ autonomously.

6. Drawbacks of bridge design pattern

  • Bridge design pattern adds to the complexity of code which might lead to a difficult situation for a fresh person joining the project
  • Double indirection – This will slightly affect execution. The deliberation needs to pass messages along to the implementor for the activity to get executed.

7. Using Bridge Design Pattern

There are certain specific cases when using bridge design pattern actually makes sense. They are specified below:

  • Adapter makes things work after they’re composed; Bridge makes them work before they are.
  • Bridge is outlined in advance to give the reflection and the implementation a chance to fluctuate freely. Adapter is retrofitted to make disconnected classes cooperate.
  • State, Strategy, Bridge (and somewhat Adapter) have comparative arrangement structures. They all offer components of the “handle/body” colloquialism. They vary in purpose – that is, they take care of various issues.
  • The structure of State and Bridge are indistinguishable (aside from that Bridge concedes orders of envelope classes, though State permits just a single). The two examples utilize a similar structure to take care of various issues: State enables a protest’s conduct to change alongside its state, while Bridge’s purpose is to decouple a deliberation from its implementation with the goal that the two can shift freely.
  • In the event that interface classes delegate the making of their implementation classes (rather than making/coupling themselves straightforwardly), at that point the plan normally utilizes the Abstract Factory example to make the implementation objects.

8. A brief comparison of Bridge Design pattern with others

Comparison always provides a better insight on any item. In this section, we contrast Bridge design pattern with others and try to understand how bridge design pattern differs from others.

  • Adapter makes things work after they’re planned; Bridge makes them work before they are.
  • Bridge is composed in advance to give the deliberation and the implementation a chance to shift freely. Adapter is retrofitted to make disconnected classes cooperate.
  • State, Strategy, Bridge (and somewhat Adapter) have comparable arrangement structures. They all offer components of the “handle/body” figure of speech. They contrast in expectation – that is, they tackle diverse issues.
  • The structure of State and Bridge are indistinguishable (aside from that Bridge concedes chains of command of envelope classes, though State permits just a single). The two examples utilize a similar structure to take care of various issues: State enables a question’s conduct to change alongside its state, while Bridge’s aim is to decouple a deliberation from its implementation with the goal that the two can fluctuate freely.
  • In the event that interface classes delegate the making of their implementation classes (rather than making/coupling themselves straightforwardly), at that point the plan generally utilizes the Abstract Factory example to make the implementation objects.

9. Java Bridge Design Pattern – Conclusion

The Bridge pattern certainly assists in reducing the replication of code for multiple classes. The bridge pattern helps in organising the code better. However, it also adds to the complexity as there is inter-linking of classes involves which increases the difficulty level for understanding the code. Occasionally, it might also make it difficult to trace due to concept of abstraction being used in this design pattern.

Bridge pattern mandates that any new person joining an enterprise scale project using this pattern, must have in-depth knowledge about this pattern. In absence of which, it would create an entry barrier for the user. In cases where the bridge classes increase or the inter-linking basically increases, it is better to avoid the design pattern rather than trying to use it as a standard.

10. Download the Source Code

That was an Example of Java Bridge Design Pattern. Below you can find the Eclipse project containing the source code of the example.

Download
You can download the full source code of this example here: Bridge Pattern.zip

Abhishek Kothari

Abhishek is a Web Developer with diverse skills across multiple Web development technologies. During his professional career, he has worked on numerous enterprise level applications and understood the technological architecture and complexities involved in making an exceptional project. His passion to share knowledge among the community through various mediums has led him towards being a Professional Online Trainer, Youtuber as well as Technical Content Writer.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button