Box<dyn ...> enables the Bridge Pattern

June 8, 2024·3 min read

Design PatternsCoding

Continouing the series about design patterns today I wanted to explore the Bridge pattern. Reading the GOF book it states "Decouple an abstraction from its implementation so that the two can vary indepedently". In Rust, the use of Box<dyn ...> makes it easier to implement the Bridge Pattern due to its ability to handle dynamic dispatch and encapsulate different implementations behind a uniform interface.

The Bridge Pattern is a structural design pattern that separates the abstraction from its implementation. This separation allows you to change both the abstraction and the implementation independently without affecting each other.

Key Components of the Bridge Pattern:

  • Abstraction: An abstract class or interface defining the high-level operations.
  • Refined Abstraction: A class that extends the abstraction to add more functionalities.
  • Implementor: An interface for the implementation classes.
  • Concrete Implementors: Classes that implement the Implementor interface and provide the concrete behavior.

Example

Let's consider a scenario where we have different types of bank accounts (like SavingsAccount and CheckingAccount) and different types of account operations (like Deposit and Withdraw). We want to decouple the accounts from the operations so that we can mix and match them independently.

Implementor trait

Concreate implementors

Abstraction Trait

Refined abstractions

Using the brindge

How Box<dyn ...> Facilitates the Bridge Pattern

  • Dynamic Dispatch: The Box<dyn ...> allows for dynamic dispatch, meaning the method to be called is determined at runtime. This is crucial for implementing the Bridge Pattern as it allows the abstraction to call the correct implementation methods without knowing the concrete class.

  • Encapsulation: Box<dyn ...> encapsulates the implementation details, adhering to the principle of hiding the complexities of the implementation from the client.

  • Flexibility: With Box<dyn ...>, we can easily swap out different implementations without changing the client code.