Design Patterns - Factory Method Pattern



So What is a Factory Method?

The Factory method is another Creational pattern. It's basically concerned with newing up your objects. It might be that you create a lot of FordFiesta objects and quite a lot of FordFocus objects. You might create these all over your program. Then something happens and you make a change to one of the types. This might lead to you having to go through and update every piece of code where you've gone var car = new FordFocus()

Why do I need a Factory Method?

There's a lot of duplication in all those new Cars. To remove the code duplication and therefore improve encapsulation we can defer all object creation of to a Factory specifically maybe a particular Factory Method for example FordFiestaFactory.CreateCar().

This also means that everyone only need depend on the abstraction, which makes eveything just that little more flexible.

Factory Method at a glance

Factory Method Code Examples

 

namespace FactoryMethod
{
    public class FordFiestaCarFactory : ICarFactory
    {
        public ICar CreateCar()
        {
            return new FordFiesta();
        }
    }
}

Above is the Factory itself, with the program using it shown below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FactoryMethod
{
    class Program
    {
        Program(ICarFactory carFactory)
        {                 
            var car = carFactory.CreateCar();
            car.Drive();            
        }


        static void Main(string[] args)
        {
            new Program(new FordFiestaCarFactory());
            new Program(new FordFocusCarFactory());
            Console.WriteLine("--------------");
            Console.ReadLine();
        }
    }


}

Recommended Reading

As before in my Abstract Factory post I'd recommend Head First Design Patterns as a really understandable guide to design patterns.

Downloads


Search

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2014