Published on

[Structural] Bridge

Authors
  • avatar
    Name
    Khánh
    Twitter

Problems

  • There are too many seperate instances in our system, How to connect them to work together?

Bridge pattern

  • The purpose of the bridge pattern is connect multiple seperated objects

Steps:

  • Determine the instance to connect
  • Init Bridge which has the function to interact with each object

Examples:

  1. Shape is the first object to connect
abstract class Shape {
  abstract name: string;
  abstract draw(): void;
}

interface Color {
  fill(shape: Shape): void;
}

class RedColor implements Color {
  fill(shape: Shape) {
    console.log(`Fill red color for ${shape.name}`);
  }
}

class GreenColor implements Color {
  fill(shape: Shape) {
    console.log(`Fill green color for ${shape.name}`);
  }
}
  1. Circle is the rest object which needs to be connected to the Shape
class Circle extends Shape {
  name: string = "Circle";
  constructor() {
    super();
  }

  draw(): void {
    console.log(`Draw circle ${this.name}`);
  }
}

class Rectangle extends Shape {
  name: string = "Rectangle";
  constructor() {
    super();
  }

  draw(): void {
    console.log(`Draw rectangle ${this.name}`);
  }
}
  1. Bridge between them
class ShapePainter {
  private shape: Shape;
  private color: Color;

  constructor(shape: Shape, color: Color) {
    this.shape = shape;
    this.color = color;
  }

  paint(): void {
    this.shape.draw();
    this.color.fill(this.shape);
  }
}
  1. Using it
const circle = new Circle();
const redCircle = new ShapePainter(circle, new RedColor());
redCircle.paint();

const rectangle = new Rectangle();
const greenRectangle = new ShapePainter(rectangle, new GreenColor());
greenRectangle.paint();

Conclusions

  • Using Bridge pattern to make cleaner to connect the collection of objects
  • Easy to maintain objects
  • Easy scale objects
  • If we need to implement another logic for the connection between objects, just define new Bridge between objects.