Tuesday, July 7, 2009

Factory Pattern in C#

I wanted to access the fields of the created classes.
Here is the code I've implemented, feel free to comment


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

namespace FactoryPattern
{

    interface Base
    {      
    }
    
    class Factory
    {
        Base derived;

        public Base GetObject(int selector)
        {
            switch (selector)
            {
                case 1:
                    derived = new Derived1();
                    break;
                case 2:
                    derived = new Derived2();
                    break;
            }
            return derived;
        }
    }


    class Derived1 : Base
    {
        public string origin = "Derived1";      
    }


    public class Derived2 : Base
    {
        public string origin = "Derived2";
        public int value = 145;
    }

    class Program
    {
        public static object GetFieldValue(string nameField, object obj)
        {
            return obj.GetType().GetField(nameField).GetValue(obj);
        }

        static void Main(string[] args)
        {
            Base obj;
            Factory f = new Factory();
            obj = f.GetObject(2);          
            var origin =  GetFieldValue("value", obj);
            System.Console.WriteLine(String.Format("{0}",origin));
            Console.ReadLine();          
        }
    }
}

No comments:

Post a Comment