The Bridge Pattern is a structural design pattern that decouples an abstraction from its implementation, allowing the two to vary independently. This pattern is useful when both the abstraction and the implementation may have multiple variations and need to be extended independently.
Note: At the end of this README.md file, I referenced the tutorial that I followed
Imagine you have different types of computers (e.g., Mac and Windows) that need to print documents using different types of printers (e.g., HP and Epson).
First you thought of this.. Creating two classes EpsonPrinterForMac
and HpPrinterForMac
and also two classes EpsonPrinterForWindows
and HpPrinterForWindows
. But this started to get messy with exponential growth (2*2) of classes.
The Bridge Pattern helps solve this problem by decoupling the abstraction (Computer) from its implementation (Printer). This allows you to extend both independently without affecting each other.
- Define the Printer Interface: This interface will have a method
PrintFile
that all concrete printers will implement. - Create Concrete Printers: Implement the
Printer
interface for different printer types (e.g., HP and Epson). - Define the Computer Interface: This interface will have methods to set a printer and print a document.
- Create Concrete Computers: Implement the
Computer
interface for different computer types (e.g., Mac and Windows). - Bridge the Abstraction and Implementation: Use the
Computer
interface to set differentPrinter
implementations and print documents.
- Printer Interface: Defines the
PrintFile
method. - Concrete Printers: HP and Epson printers implementing the
Printer
interface. - Computer Interface: Defines methods to set a printer and print.
- Concrete Computers: Mac and Windows computers implementing the
Computer
interface.
The main function demonstrates how different computers can use different printers interchangeably.
Printing file with a EPSON printer...
Printing file with a HP printer...
Printing file with a EPSON printer...
Printing file with a HP printer...
- Decoupling Abstraction and Implementation: Allows both to vary independently.
- Increased Flexibility: You can change or extend the abstraction and implementation hierarchies independently.
- Simplified Code Maintenance: Changes in the implementation do not affect the client code.
Refactoring Guru: Bridge Pattern
The example problem and solution at Refactoring Guru of RedCircle
, RedSquare
, BlueCircle
, BlueSquare
I found so great to learn! I recommend readers to check their tutorial for better learning!