Wednesday 29 November 2017

Simple Factory Pattern

The simple factory pattern is probably the most common pattern you'll ever see; it's fairly simple in concept and implementation. It can be thought of as a central location to create instances of objects. take a look at the following example.

interface IHourly
{
    double HourlyRate { get; set; }
}

interface ISalery
{
    int Salery { get; set; }
    double Bonus { get; }
}

class Person
{
    static int runningId = 0;
    public int Id { get; } = runningId++;
    public string Name { get; set; }
    public override string ToString() => $"{Id}) {Name}";
}

class EmployeePersonIHourly
{
    public double HourlyRate { get; set; }
    public override string ToString() => $"{base.ToString()} ${HourlyRate * 40 * 52}";
}

class PartnerPersonISalery
{
    public int Salery { get; set; }
    public double Bonus { get => 1.1; }
    public override string ToString() => $"{base.ToString()} ${Salery * Bonus}";

}

what we have above is three objects  Person, Employee and Partner; Person is the common base for employee and partner. Now if we had an array of strings that represented various partners and employees such as the following.

class Program
{
    static void Main(string[] args)
    {
        var staffFactory = new StaffFactory();
        var data = new [] { "Pawel $100000", "Magda $150000", "Marin $50.00", "Bryne $45.53" };
    }

}

it would prove to be a pain to extract the data parse it, decide whether it's an employee or a partner then create an instance of that object, well it's only natural to create a function to do that grunt work for use, and hence a factory.

class StaffFactory
{
    public Person ParseStaff(string data)
    {
        var dataValues = data.Split(' ');
        dataValues[1] = dataValues[1].TrimStart('$');
        double wage;
        int salery;

        if (int.TryParse(dataValues[1], out salery))
            return new Partner { Name = dataValues[0], Salery = salery };
        else if (double.TryParse(dataValues[1], out wage))
            return new Employee { Name = dataValues[0], HourlyRate = wage };

        return null;
    }
}

class Program
{
    static void Main(string[] args)
    {
        var staffFactory = new StaffFactory();
        var data = new string[] { "Pawel $100000", "Magda $150000", "Marin $50.00", "Bryn $45.53" };

        foreach (var d in data)
            Console.WriteLine(staffFactory.ParseStaff(d).ToString());
    }
}

an tada, that's all there really is to a simple factory pattern, it's just a function that takes in some parameters and returns objects. One caveat to mention is that there is such a thing as a Factory Method Pattern, in which the only difference is that the factory adheres to an abstraction.