Wednesday, May 9, 2012

Simple Factory


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

namespace Factory
{
    class Program
    {
        static void Main(string[] args)
        {
            ProductFactory pf = new ProductFactory();
            Product p = pf.createProduct("OneProduct");
            Console.ReadLine();
        }
    }

    public class ProductFactory
    {
        public Product createProduct(String ProductID){
            //if (ProductID=="OneProduct")
            //    return new OneProduct();
            //else if (ProductID=="TwoProduct")
            //    return new TwoProduct();
            //else
            //    return null;


            Assembly assembly = Assembly.GetExecutingAssembly(); //Get the current assembly object
            AssemblyName assemblyName = assembly.GetName(); //Get the name of the assembly (this will include the public token and version number
            Type t = assembly.GetType(assemblyName.Name + "." + ProductID); //Use just the name concat to the class chosen to get the type of the object
            return (Product)Activator.CreateInstance(t); //Create the object, cast it and return it to the caller
        }

    }

    public abstract class Product
    {
    }

    public class OneProduct : Product
    {
        public OneProduct()
        {
        }
    }

    public class TwoProduct : Product
    {
        public TwoProduct()
        {
        }     
    }
}

No comments:

Post a Comment