factory design pattern example

Example 1: where design pattern factory is used

where design pattern factory is used

The Factory Method pattern is generally used in the following situations: A class cannot anticipate the type of objects it needs to create beforehand. A class requires its subclasses to specify the objects it creates. You want to localize the logic to instantiate a complex object.

The factory design pattern is used when we have a superclass with multiple sub-classes and based on input, we need to return one of the sub-class. This pattern takes out the responsibility of the instantiation of a class from the client program to the factory class.

The Factory Method design pattern is used by first defining a separate operation, a factory method, for creating an object, and then using this factory method by calling it to create the object. This enables writing of subclasses that decide how a parent object is created and what type of objects the parent contains.

Example 2: simple factory pattern

enum FanType
{
    TableFan,
    CeilingFan,
    ExhaustFan
}

interface IFan
{
    void SwitchOn();
    void SwitchOff();
}

class TableFan : IFan {.... }

class CeilingFan : IFan {.... }

class ExhaustFan : IFan {..... }

interface IFanFactory
{
    IFan CreateFan(FanType type);
}

class FanFactory : IFanFactory
{
    public IFan CreateFan(FanType type)
    {
        switch (type)
        {
            case FanType.TableFan:
                return new TableFan();
            case FanType.CeilingFan:
                return new CeilingFan();
            case FanType.ExhaustFan:
                return new ExhaustFan();
            default:
                return new TableFan();
        }
    }
}

//The client code is as follows:

static void Main(string[] args)
{
        IFanFactory simpleFactory = new FanFactory();
        // Creation of a Fan using Simple Factory
        IFan fan = simpleFactory.CreateFan(FanType.TableFan);
        // Use created object
        fan.SwitchOn();

        Console.ReadLine();
 }

Tags:

Misc Example