Monday, November 11, 2013

Factory Method Design pattern

Hello

First, i wish publish code and class diagram, and use it as a reference after.

Code:
namespace FactoryMethodDP
{
    public interface ICreatedClass
    {
        string GetName();
    }

    public class CreatedClassA : ICreatedClass
    {
        public string GetName() { return "A"; }
    }

    public class CreatedClassB : ICreatedClass
    {
        public string GetName() { return "B"; }
    }


    public interface ICreator
    {
        ICreatedClass FactoryMethod();
    }

    public class ConcreteCreatorA : ICreator
    {
        public ICreatedClass FactoryMethod() { return new CreatedClassA(); }
    }

    public class ConcreteCreatorB : ICreator
    {
        public ICreatedClass FactoryMethod() { return new CreatedClassB(); }
    }
}

Class Diagram:
Fig 1:class diagram without associations

Fig 2: class diagram with client associations

Fig 3: class diagram with associations inside of Factory Method

About class diagrams: while first is more simple, clear and understandable, the second closer to real life - there can be seen who should know about who.

Factory Method, like Simple Factory, served the client for creating objects without knowledge about objects, only about its interface. So, instantiation of objects is encapsulated

But, there is some differences between Factory Method and Simple Factory
There some minor differences, like static method in Simple Factory etc. The really goal, IMHO, Factory Method do not violates Open-Closed Principle. As a developer, you can add pairs (pair, because if add Created class need add Creator class too. In current design) of classes without need to change other classes. 
For example, let's think about CPU Factory Method.  Approach of adding new type of CPU (for example ARM) is different in Simple Factory and Factory Method. 
In Simple Factory i need add enum and change factory class (in switch statement i should add new case, so it Open-Closed Principle violation). 
In Factory Method i only add pairs of classes (one implements ICreator and other implements ICreatedClass), without change other classes (Fig 1).

Client, in both Design Patterns, should knows 3 things (Fig 2): 
  • interface of created object
  • interface of creator 
  • concrete creators in Factory Method and enum in Simple Factory
 So, here both patterns are same +-.

That's all

No comments:

Post a Comment