首页 > 代码库 > 简单工厂

简单工厂

本简单工厂,

将实体类名字写入配置文件,工厂类通过反射穿件实体

主方法

class Program
    {
        static void Main(string[] args)
        {
            IPeople p = Factory.CreateInstanceReflect();
            p.Say();

            Console.WriteLine("-------------");

            IPeople p1 = new Factory().CreateInstanceReflect1();
            p1.Say();

            Console.ReadKey();
        }
    }

工厂方法

public class Factory
    {
        public static IPeople CreateInstanceReflect()
        {
            string config = System.Configuration.ConfigurationSettings.AppSettings["InstanceReflect"];
            string assemblyName=config.Split(,)[0];
            string typeName = config.Split(,)[1];
            return (IPeople)Activator.CreateInstance(assemblyName, typeName).Unwrap();
        }

        public IPeople CreateInstanceReflect1()
        {
            string config = System.Configuration.ConfigurationSettings.AppSettings["InstanceReflect1"];

            return (IPeople)this.GetType().Assembly.CreateInstance(config); ;
        }
    }

配置文件

  <appSettings>
    <add key="InstanceReflect" value=http://www.mamicode.com/"简单工厂模式,简单工厂模式.Teacher"></add>
    <add key="InstanceReflect1" value=http://www.mamicode.com/"简单工厂模式.Student"></add>
  </appSettings>

其他基础类

  namespace 简单工厂模式
{
  public interface IPeople
    {
        void Say(); 
    }

    public class Student:IPeople
    {
        public void Say()
        {
            Console.WriteLine("创建了学生");
        }
    }


    public class Teacher :IPeople
    {
        public void Say()
        {
            Console.WriteLine("创建了老师");
        }
    }
}

 

简单工厂