A day with .Net

My day to day experince in .net

Factory Pattern in C#

Posted by vivekcek on September 11, 2012

creates objects without exposing the instantiation logic to the client.
refers to the newly created object through a common interface

The implementation is really simple

1. The client needs a product, but instead of creating it directly using the new operator, it asks the factory object for a new product, providing the information about the type of object it needs.
2.The factory instantiates a new concrete product and then returns to the client the newly created product.
3.The client uses the products as abstract products without being aware about their concrete implementation

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Threading.Tasks;

namespace SimpleFactory
{
    class Program
    {
        static void Main(string[] args)
        {
            ProductFactory factory = new ProductFactory();
            IProduct product = factory.CreateProduct("Book");
        }
    }
    class ProductFactory
    {
        Dictionary<string, Type> Products;
        public ProductFactory()
        {
            LoadProducts();
        }
        public IProduct CreateProduct(string productName)
        {
            Type t = GetType(productName);
            IProduct product = Activator.CreateInstance(t) as IProduct;
            return product;
        }

        private Type GetType(string productName)
        {
            foreach (var product in Products)
            {
                if (Products.Keys.Contains(productName))
                    return Products[product.Key];
            }
            return null;
        }
        private void LoadProducts()
        {
            Products = new Dictionary<string, Type>();
            Type[] produtTypes = Assembly.GetExecutingAssembly().GetTypes();
            foreach (Type product in produtTypes)
            {
                if (product.GetInterface(typeof(IProduct).ToString()) != null)
                    Products.Add(product.Name.ToString(), product);
            }
        }
    }
    interface IProduct
    {
        string ProductName { get; }
    }
    class Book : IProduct
    {

        public string ProductName
        {
            get { return "Book"; }
        }
    }
    class MobilePhone : IProduct
    {

        public string ProductName
        {
            get { return "MobilePhone"; }
        }
    }
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s