Structural Design Pattern: Bridge Pattern - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

Structural Design Pattern: Bridge Pattern

Share This
The Bridge Pattern advocates for the separation of the functional abstraction from its implementation, allowing them to evolve independently.

The Bridge Pattern is alternatively referred to as Handle or Body.

The advantage of the Bridge Pattern is its ability to decouple an abstraction from its implementation, allowing them to vary independently. This promotes flexibility, extensibility, and maintainability in software design.

It allows for the distinction between the implementation and the interface. It enhances the ability to extend or expand. It enables the concealment of implementation specifics from the customer.

Application of the Bridge Pattern
  • when there is a desire to avoid a permanent connection between the functional abstraction and its implementation. 
  • when there is a need to extend both the functional abstraction and its implementation using sub-classes. 
  • It is primarily utilized in locations where modifications to the implementation do not impact the clients.

Source code of Printer.java
package com.t4b.test.java.dp.sp.bp; interface Printer { public void print(int radius, int x, int y); }
Source code of BlackPrinter.java
package com.t4b.test.java.dp.sp.bp; class BlackPrinter implements Printer { @Override public void print(int radius, int x, int y) { System.out.println("Black: " + radius + ", x: " + x + ", " + y + "]"); } }
Source code of ColorPrinter.java
package com.t4b.test.java.dp.sp.bp; class ColorPrinter implements Printer { @Override public void print(int radius, int x, int y) { System.out.println("Color: " + radius + ", x: " + x + ", " + y + "]"); } }
Source code of Shape.java
package com.t4b.test.java.dp.sp.bp; abstract class Shape { protected Printer printer; protected Shape(Printer p) { this.printer = p; } public abstract void draw(); }
Source code of Circle.java
package com.t4b.test.java.dp.sp.bp; class Circle extends Shape { private int x, y, radius; public Circle(int x, int y, int radius, Printer draw) { super(draw); this.x = x; this.y = y; this.radius = radius; } public void draw() { printer.print(radius, x, y); } }
Source code of TestMain.java
package com.t4b.test.java.dp.sp.bp; public class TestMain { public static void main(String[] args) { Shape redCircle = new Circle(100, 100, 10, new ColorPrinter()); Shape blackCircle = new Circle(100, 100, 10, new BlackPrinter()); redCircle.draw(); blackCircle.draw(); } }

Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.