Monday, November 21, 2011

Factory Method Design Pattern

This is some sample code from C# 3.0 Design Patterns by Judith Bishop outlining the Factory Method Design Pattern:

using System;
  using System.Collections;

  class FactoryPattern {
  
  // Factory Method Pattern       Judith Bishop 2006
  //  Example of exporting from different suppliers
    
  interface IProduct {
    string ShipFrom();
  }

  class ProductA : IProduct {
    public String ShipFrom () {
      return " from South Africa";
    }
  }
  
  class ProductB : IProduct {
    public String ShipFrom () {
            return "from Spain";
    }
  }

  class DefaultProduct : IProduct {
    public String ShipFrom () {
            return "not available";
    }
  }

  class Creator {
    public  IProduct FactoryMethod(int month) {
      if (month >= 4 && month <=11)
        return new ProductA();
      else 
      if (month == 1 || month == 2 || month == 12)
        return new ProductB();
      else 
        return new DefaultProduct();
    }
  }
  
    static void Main() {
      Creator c = new Creator();
      IProduct product;
        
      for (int i=1; i<=12; i++) {
        product = c.FactoryMethod(i);
        Console.WriteLine("Avocados "+product.ShipFrom());
      }
    }
  }

So by looking at the code, you can probably get a good feel for what the code is trying to accomplish.

There are 3 products which all need to implement common shipping functionality but need to ship from 3 different locations. Therefore, this is a perfect candidate for implementing an Interface across all of the class implementations. By implementing a common Interface, the classes can easily be swapped for one another (called "polymorphism"). Since all of the classes are interchangeable, there only needs to be a set of criteria which dictates which class is actually instantiated and utilized within the Main method.

In this case, the Factory method is responsible for accepting that parameter (in this case, the month) and then returning the appropriate instance of the class based on the internally developed logic which has been conveniently encapsulated into a single method. The Main method can now simply be oblivious to the actual instance of the class that is required. The class is returned as an instance of an Interface and the only parameter that is required to be known is the month. The Factory Method in this manner also assists in the principles of encapsulation and decoupling.

No comments:

Post a Comment