Monday, November 11, 2013

Simple Factory Design Pattern

Hello

It is very reasonable and simple code structure: create different objects in run-time

But, it violate Open-Closed Principle. Why? If we add new constructed type we need change enum and change SimpleFactory.
But, do not worry, maybe it will feet Your needs. Maybe Types will never be added. For example, there 12 types of months and in future no month will be added, becouse there is no 13 months in year :-)

Class Diagram:





Client should know:
1. Which object to create. It can be enum (like in example, "ObjectType") or string or something else.
2. SimpleFactory and its static method Create
3. Created object interface (like in example, "IFactoryInterface")

My example - is factory of processors: Intel, AMD and VIA

Code example:

Code:
namespace SimpleFactoryDP
{
    public enum CPUType { Intel, AMD, VIA, }

    public interface ICPU
    {
        string GetName();
        double GetSpeed();
        int GetPinsAmount();
    }

    public static class CPUFactory
    {
        public static ICPU Create(CPUType type)
        {
            ICPU cpu = null;

            switch (type)
            {
                case CPUType.AMD:
                    cpu = new AMD();
                    break;
                case CPUType.Intel:
                    cpu = new Intel();
                    break;
                case CPUType.VIA:
                    cpu = new VIA();
                    break;
            }

            return cpu;
        }
    }

    public class Intel : ICPU
    {
        public string GetName() { return "Intel CPU. Very Good CPU"; }
        public double GetSpeed() { return 6.78; }
        public int GetPinsAmount() { return 400; }
    }

    public class AMD : ICPU
    {
        public string GetName() { return "AMD CPU. Very Well and cheap CPU"; }
        public double GetSpeed() { return 5.99; }
        public int GetPinsAmount() { return 420; }
    }

    public class VIA : ICPU
    {
        public string GetName() { return "VIA CPU. Very Cheap"; }
        public double GetSpeed() { return 4.11; }
        public int GetPinsAmount() { return 100; }
    }
}

Using:
ICPU cpuIntel = CPUFactory.Create(CPUType.Intel);
Assert.AreEqual(cpuIntel.GetName(), "Intel CPU. Very Good CPU");
Assert.AreEqual(cpuIntel.GetSpeed(), 6.78);
Assert.AreEqual(cpuIntel.GetPinsAmount(), 400);

That's all

No comments:

Post a Comment