Design Patterns -- Abstract Factory Pattern


Abstract Factory Pattern is a type of Creational Pattern .

What is Abstract Factory Pattern?

Let’s go by Definition in Gang of Four (GOF)

Provide an interface for creating families of related or dependent objects without specifying their concrete classes

Let’s look into this pattern for an example where we are products which can be categorized for Basic, Regular, Seasonal etc.

We will create an interface for the abstract product as show below
    interface IProductFactory
    {
        Hashtable ProductProperties();
    }

The next step we will create a concrete product class

    class BasicProduct : IProductFactory
    {
        public Hashtable ProductProperties()
        {
            Hashtable ht = new Hashtable();
            ht["Type"] = "FMCG";
            ht["Name"] = "Soap";
            return ht;
        }
    }

    class SeasonalProduct : IProductFactory
    {
        public Hashtable ProductProperties()
        {
            Hashtable ht = new Hashtable();
            ht["Type"] = "Seasonal";
            ht["Name"] = "Mango";
            return ht;
        }
    }

       
Now let’s create a factory class which uses the product interface

    class ProductBase
    {
        IProductFactory _abstarctFactory;
        Hashtable _productProperties;

        public IProductFactory Factory
        {
            get { return _abstarctFactory; }
            set { _abstarctFactory = value; }
        }

        public Hashtable ProductProperties
        {
            get
            {
                _productProperties = Factory.ProductProperties();
                return _productProperties;
            }
        }
    }

In the last step, let’s create a concrete class which uses the factory class

    class ProductBasic : ProductBase
    {
        public ProductBasic()
        {
            Factory = new BasicProduct();
        }
    }

    class ProductSeasonal : ProductBase
    {
        public ProductSeasonal()
        {
            Factory = new SeasonalProduct();
        }
    }


Let’s use this in a sample application as shown below
     
     ProductBasic _basic = new ProductBasic();
     foreach (DictionaryEntry e in _basic.ProductProperties)
     {
          Console.WriteLine(e.Key + ":" + e.Value);
          Console.ReadLine();
     }

       ProductSeasonal _seasonal = new ProductSeasonal();
   foreach (DictionaryEntry e1 in _seasonal.ProductProperties)
   {
        Console.WriteLine(e1.Key + ":" + e1.Value);
        Console.ReadLine();
   }

The output of the same is as shown below




Hope this was helpful. Please do drop your comments.

Comments

Popular posts from this blog

Jesus - God Thinks of you.

ASP.NET 4.0 Feature - URL Routing

Tips on JQuery Intellisense in VS 2008