DEV Community

Juarez Júnior
Juarez Júnior

Posted on

C# Design Pattern: Bridge

The Bridge pattern is used when you want to separate how something is done (implementation) from what needs to be done (abstraction). This helps combine different parts flexibly. For example, if you have different shapes (like circles and squares) and different colors (like red and blue), the Bridge lets you mix and match shapes and colors without needing a new class for each combination.

C# Code Example:

// Interface for colors
public interface IColor
{
    void ApplyColor();
}

// Implementation for the red color
public class Red : IColor
{
    public void ApplyColor()
    {
        Console.WriteLine("Applying red color.");
    }
}

// Implementation for the blue color
public class Blue : IColor
{
    public void ApplyColor()
    {
        Console.WriteLine("Applying blue color.");
    }
}

// Shape abstraction
public abstract class Shape
{
    protected IColor color;

    protected Shape(IColor color)
    {
        this.color = color;
    }

    public abstract void Draw();
}

// Circle implementation
public class Circle : Shape
{
    public Circle(IColor color) : base(color) { }

    public override void Draw()
    {
        Console.WriteLine("Drawing a circle.");
        color.ApplyColor();
    }
}

// Square implementation
public class Square : Shape
{
    public Square(IColor color) : base(color) { }

    public override void Draw()
    {
        Console.WriteLine("Drawing a square.");
        color.ApplyColor();
    }
}

class Program
{
    static void Main(string[] args)
    {
        // Drawing a red circle
        Shape redCircle = new Circle(new Red());
        redCircle.Draw();  // Output: Drawing a circle. Applying red color.

        // Drawing a blue square
        Shape blueSquare = new Square(new Blue());
        blueSquare.Draw();  // Output: Drawing a square. Applying blue color.
    }
}
Enter fullscreen mode Exit fullscreen mode

Code Explanation:

In this example, we have shapes like Circle and Square and colors like Red and Blue. The Bridge pattern separates the logic of drawing the shape from applying the color. This allows you to draw a circle or square with any color, without needing a specific class for each combination (e.g., “Red Circle” or “Blue Square”). The code draws a red circle and a blue square.

Conclusion:

The Bridge pattern makes it easier when you need to combine different types of shapes and colors (or other attributes) without creating a new class for each combination. This makes the code simpler and easier to maintain.

Source code: GitHub

Top comments (0)