Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Factory Method Pattern clarification

My understanding of Factory Method Pattern is (Correct me if i am wrong)

Factory Method Pattern

"Factory Method allow the client to delegates the product creation (Instance Creation) to the subclass".

There are two situation in which we can go for creating Factory Method pattern.

(i) When the client is restricted to the product (Instance) creation.

(ii) There are multiple products available.But a decision to be made which product instance need to be returned.

If you want to create Abstract Method pattern

  • You need to have abstract product
  • Concrete Product
  • Factory Method to return the appropriate product.

Example :

public enum ORMChoice
{
  L2SQL,
  EFM,
  LS,
  Sonic
}
//Abstract Product
public interface IProduct
{
   void ProductTaken();
}
//Concrete Product
public class LinqtoSql : IProduct
{
  public void ProductTaken()
  {
    Console.WriteLine("OR Mapping Taken:LinqtoSql");
  }
 }
//concrete product
 public class Subsonic : IProduct
 {
    public void ProductTaken()
    {
       Console.WriteLine("OR Mapping Taken:Subsonic");
    }
 }
//concrete product
 public class EntityFramework : IProduct
 {
    public void ProductTaken()
    {
       Console.WriteLine("OR Mapping Taken:EntityFramework");
    }
  }
//concrete product
 public class LightSpeed : IProduct
 {
   public void ProductTaken()
   {
     Console.WriteLine("OR Mapping Taken :LightSpeed");
    }
  }

 public class Creator
 {
    //Factory Method 
    public IProduct ReturnORTool(ORMChoice choice)
    {
      switch (choice)
      {
        case ORMChoice.EFM:return new EntityFramework();
        break;
        case ORMChoice.L2SQL:return new LinqtoSql();
        break;
        case ORMChoice.LS:return new LightSpeed();
        break;
        case ORMChoice.Sonic:return new Subsonic();
        break;
        default: return null;
      }
  }

 }

**Client**

Button_Click()
{
 Creator c = new Creator();
 IProduct p = c.ReturnORTool(ORMChoice.L2SQL);
 p.ProductTaken();

}

Is my understanding of Factory Method is correct?

like image 890
user274364 Avatar asked Mar 29 '10 18:03

user274364


1 Answers

What you have there is actually more of an Abstract Factory Pattern, only that you factory (Creator) is not abstract. The factor method pattern is specifically useful for subclassing:

class A {
public:
    A() : m_Member( GetMember() ) 
    {
    }
protected:
    virtual ISomeInterface * GetMember() { // default impl here }
private:
    ISomeInterface * m_Member;
}

Now subclasses of A can override GetMember to make the superclass use a specific implementation of ISomeInterface.

like image 139
Björn Pollex Avatar answered Oct 05 '22 00:10

Björn Pollex