Factory Method Pattern

 

Comments

 

Difficult to understand second implementation but first basically creates any defined derived (concrete) class based on an input parameter within a switch.

 

Code

 

public interface IPeople
{
    string GetName();
}

public class Villagers : IPeople
{
    public string GetName()
    {
        return "Village Person";
    }
}

public class CityPeople : IPeople
{
    public string GetName()
    {
        return "City Person";
    }
}

public enum PeopleType
{
    Rural,
    Urban
}

/// 
/// Implementation of Factory - Used to create objects
/// 
public class Factory
{
    public IPeople GetPeople(PeopleType type)
    {
        switch (type)
        {
            case PeopleType.Rural:
                return new Villagers();
            case PeopleType.Urban:
                return new CityPeople();
            default:
                throw new NotSupportedException()
        }
    }
}

In the above code you can see the creation of one interface called IPeople and implemented two classes from it as Villagers and CityPeople.

 

Based on the type passed into the factory object, we are sending back the original concrete object as the Interface IPeople.

A Factory method is just an addition to Factory class. It creates the object of the class through interfaces but on the other hand, it also lets the subclass decide which class is instantiated.

 

public interface IProduct
{
    string GetName();
    string SetPrice(double price);
}

public class Phone : IProduct 
{
    private double _price;
    #region Product Members

    public string GetName()
    {
        return "Apple TouchPad";
    }

    public string SetPrice(double price)
    {
        this._price = price;
        return "success";
    }

    #endregion
}

/* Almost same as Factory, just an additional exposure to do something with the created method */
public abstract class ProductAbstractFactory
{
    protected abstract IProduct DoSomething();

    public IProduct GetObject() // Implementation of Factory Method.
    {
        return this.DoSomething();
    }
}

public class PhoneConcreteFactory : ProductAbstractFactory
{
    protected override IProduct DoSomething()
    {
        IProduct product = new Phone();
        //Do something with the object after you get the object. 
        product.SetPrice(20.30);
        return product;
    }
}

You can see we have used GetObject in concreteFactory. As a result, you can easily call DoSomething() from it to get the IProduct. You might also write your custom logic after getting the object in the concrete Factory Method. The GetObject is made abstract in the Factory interface.