Printed from www.rmfusion.com A Developer website designed for Developers

Factory Method Pattern Code Review

Code Download

Define the Factory Object

The Factory class (object) defines the FactoryMethod() method, which decides which subclass to instantiated.

class Factory { public Product.IProduct FactoryMethod(Int32 month) { if (month >= 4 && month <=11) { return new Product.ProductA(); } else if (month == 1 || month == 2 || month == 12) { return new Product.ProductB(); } else { return new Product.ProductC(); } } }

Define the Product Interface and Handler Objects

Define the Product class containing the IProduct interface and inherited Product subclasses.

class Product { public interface IProduct { String ShipFrom(); }
internal class ProductA : IProduct { public String ShipFrom() { return (" from South Africa."); } }
internal class ProductB : IProduct { public String ShipFrom() { return (" from Spain."); } }
internal class ProductC : IProduct { public String ShipFrom() { return (" not available."); } } }

Use the Factory Method Pattern

The Program class creates an instance of the Factory class, and creates instance of IProduct interface.

class Program { static void Main(string[] args) { Factory factory = new Factory(); Product.IProduct product;
for (Int32 i = 1; i <= 12; i++) { product = factory.FactoryMethod(i); Console.WriteLine(String.Format("Product {0}", product.ShipFrom())); }
Console.Read(); } }

During the iteration process a specific Product subclass is created by the FactoryMethod() method and relevant ShipFrom() method invoked on the subclass.