工厂方法模式结构图:

简单工厂模式在创建操作符对象工厂时违背了开放-封闭原则:因此出现了工厂方法模式。

本例以两个数的加法和减法操作为例:

操作符类(OperateNum):

namespace Factory_Method_Pattern.CLASS
{
    abstract class OperateNum
    {
        private decimal numberA;
        private decimal numberB;

        /// <summary>
        /// 操作数A
        /// </summary>
        public decimal NumberA
        {
            get { return numberA; }
            set { numberA = value; }
        }

        /// <summary>
        /// 操作数B
        /// </summary>
        public decimal NumberB
        {
            get { return numberB; }
            set { numberB = value; }
        }

        public abstract decimal Result();
    }
}
View Code

加法类(Add):继承于操作符类(OperateNum)

namespace Factory_Method_Pattern.CLASS
{
    class Add:OperateNum
    {
        public override decimal Result()
        {
            decimal result;
            result = NumberA + NumberB;
            return result;
        }
    }
}
View Code

减法类(Sub):继承于操作符类(OperateNum)

namespace Factory_Method_Pattern.CLASS
{
    class Sub:OperateNum
    {
        public override decimal Result()
        {
            decimal result;
            result = NumberA - NumberB;
            return result;
        }
    }
}
View Code

工厂接口(IFactory):

namespace Factory_Method_Pattern.CLASS
{
    interface IFactory
    {
        OperateNum CreateOperate();
    }
}
View Code

加法工厂(AddFactory):继承于工厂接口(IFactory)

namespace Factory_Method_Pattern.CLASS
{
    class AddFactory:IFactory
    {
        public OperateNum CreateOperate()
        {
            return new Add();
        }
    }
}
View Code

减法工厂(SubFactory):继承于工厂接口(IFactory)

namespace Factory_Method_Pattern.CLASS
{
    class SubFactory:IFactory
    {
        public OperateNum CreateOperate()
        {
            return new Sub();
        }
    }
}
View Code

客户端代码:(TestMain)

namespace Factory_Method_Pattern
{
    class TestMain
    {
        static void Main(string[] args)
        {
            IFactory operFactory = new AddFactory();
            OperateNum oper = operFactory.CreateOperate();
            oper.NumberA = 1;
            oper.NumberB = 2;
            Console.WriteLine("相加结果为:{0}",oper.Result());

            IFactory operFactory1 = new SubFactory();
            OperateNum oper1 = operFactory1.CreateOperate();
            oper1.NumberA = Convert.ToDecimal(Console.ReadLine());
            oper1.NumberB = Convert.ToDecimal(Console.ReadLine());
            Console.WriteLine("相减结果为:{0}", oper1.Result());

            Console.ReadLine();
        }
    }
}
View Code

 

 

 

 

 

posted on 2013-08-07 22:07  zxd543  阅读(140)  评论(0编辑  收藏  举报