首页 > 代码库 > 工厂方法模式(Factory Method)

工厂方法模式(Factory Method)

工厂方法模式:定义一个用于创建对象的接口,让子类来决定实例化哪一个类。工厂方法使一个类的实例化延迟到子类。

 

简单工厂模式的最大有点在于工厂勒种包含了必要的逻辑判断,根据客户端的选择条件动态实例化相关的类,对客户端来说,去除了与具体产品的依赖。

工厂方法模式实现时,客户端需要决定实例化哪一个工厂来实现运算类,选择判断的问题还是存在的。工厂方法吧简单工厂的内部逻辑转移到了客户端代码来进行。

 

/// <summary>
    /// 运算类
    /// </summary>
   public class Operation
    {
        public double NumA { get; set; }

        public double NumB { get; set; }

        public virtual double GetResult()
        {
            double result = 0;
            return result;
        }
    }

    /// <summary>
    /// 加法类
    /// </summary>
   public class OperationAdd : Operation
    {
        public override double GetResult()
        {
            double result = 0;
            result = NumA + NumB;
            return result;
        }
    }

    /// <summary>
    /// 减法类
    /// </summary>
    public class OperationSub : Operation
    {
        public override double GetResult()
        {
            double result = 0;
            result = NumA - NumB;
            return result;
        }
    }


    /// <summary>
    /// 工厂接口
    /// </summary>
    public interface IFactory
    {
        Operation FactoryMethod();
    }

    /// <summary>
    /// 加法工厂
    /// </summary>
    public class AddFactory : IFactory
    {
        public Operation FactoryMethod()
        {
            return new OperationAdd();
        }
    }

    /// <summary>
    /// 减法工厂
    /// </summary>
    public class SubFactory : IFactory
    {
        public Operation FactoryMethod()
        {
            return new OperationSub();
        }
    }

   class Program
    {
        static void Main(string[] args)
        {
            IFactory[] fac = new IFactory[2];
            fac[0] = new AddFactory();
            fac[1] = new SubFactory();

            Operation oper;
            oper = fac[0].FactoryMethod();
            oper.NumA=10;
            oper.NumB=5;
            Console.WriteLine("Called By {0}", oper.GetType().Name);
            Console.WriteLine("Result={0}", oper.GetResult().ToString());
         
            oper = fac[1].FactoryMethod();
            oper.NumA = 10;
            oper.NumB = 5;
            Console.WriteLine("Called By {0}", oper.GetType().Name);
            Console.WriteLine("Result={0}", oper.GetResult().ToString());

            Console.ReadKey();
        }
    }

http://www.cnblogs.com/lxblog/p/4119426.html

工厂方法模式(Factory Method)