C# Design Patterns – Difference Between Bridge and Factory Pattern

cfactory-method

What is the difference between Bridge and Factory Pattern? both the pattern seems to instanitae the class depending upon the logic from the client side.

Factory Pattern

interface IFactory {
    void GetProduct();
}
class Germany : IFactory {
    public void GetProduct() {
        Console.WriteLine("germany");
    }
}
class Russia : IFactory {
    public void GetProduct() {
        Console.WriteLine("Russia");
    }
}
class Canada : IFactory {
    public void GetProduct() {
        Console.WriteLine("Canada");
    }
}
class Component {
    IFactory factory;
    public Component(IFactory component) {
        this.factory = component;
    }
    public void BuyProduct() {
        factory.GetProduct();
    }
}
class Client {
    static void Main() {
        Component component = new Component(new Canada());
        component.BuyProduct();

        Console.Read();
    }
}

Bridge Pattern

interface IBridge
{
    void print();
}
class ImplementationA : IBridge
{
    public void print()
    {
        Console.WriteLine("implementation A");
    }
}
class ImplementationB : IBridge
{
    public void print()
    {
        Console.WriteLine("implementation A");
    }
}
class Abstraction
{
    IBridge bridge;
    public Abstraction(IBridge bridge)
    {
        this.bridge = bridge;
    }
    public void caller()
    {
        bridge.print();
    }
}
class Client
{
    static void Main()
    {
        new Abstraction(new ImplementationA()).caller();
    }
}

in both Factory and Bridge pattern we can see that the class is instantiated from the client on some logic. Is not both the code doing the same thing. In Factory pattern, clients logic decide which class should be instantiated which is the same case with Bridge Pattern as well.

so what really is the change,please help me understand it

Best Answer

This should help

The Bridge Separates an object’s interface from its implementation

The Factory Method - Creates an instance of several derived classes