Skip to content

Latest commit

Β 

History

History
87 lines (65 loc) Β· 1.72 KB

File metadata and controls

87 lines (65 loc) Β· 1.72 KB

πŸŒ‰ Bridge

Category: Structural

πŸ“– Description

The Bridge pattern separates an abstraction from its implementation so that the two can vary independently.

πŸ› οΈ Purpose: Decouple abstraction and implementation.


πŸ”§ Structure

classDiagram
    class Abstraction {
        - Implementor implementor
        + operation()
    }
    class RefinedAbstraction
    class Implementor {
        +operationImpl()
    }
    class ConcreteImplementor

    Abstraction <|-- RefinedAbstraction
    Implementor <|-- ConcreteImplementor
    Abstraction --> Implementor
Loading

πŸ’» Java 21 Example

Interfaces

public interface Implementor {
    void operationImpl();
}

public abstract class Abstraction {
    protected final Implementor implementor;

    protected Abstraction(final Implementor implementor) {
        this.implementor = implementor;
    }

    public abstract void operation();
}

Concrete

public final class ConcreteImplementor implements Implementor {
    @Override
    public void operationImpl() {
        System.out.println("Concrete implementation");
    }
}

public final class RefinedAbstraction extends Abstraction {

    public RefinedAbstraction(final Implementor implementor) {
        super(implementor);
    }

    @Override
    public void operation() {
        implementor.operationImpl();
    }
}

Usage

public final class Demo {
    public static void main(final String[] args) {
        Implementor implementor = new ConcreteImplementor();
        Abstraction abstraction = new RefinedAbstraction(implementor);
        abstraction.operation();
    }
}