代码来源参谋大话设计形式那本书

稳步的做记录,做最强大的要好

看了牛皮设计形式之后感触很深,开采本人还应该有为数不菲学学的事物,设计软件并非一两句代码把效果写完了就行,须要惦记的源委有过多

代码来源仿照效法大话设计情势那本书,这里在博客里记录一下,不大概每一遍都去翻书,可是在博客里面是丰富好找的。

范例为三个简短工厂形式的计算器,首先先制造一个总计器运算所供给动用的数据模型,在java个中也叫bean,便是一个虚无的类,这里大家先创制贰个Operation类

public class Operation
    {
        private double _numberA = 0;
        private double _numberB = 0;

        public double NumberA
        {
            get { return _numberA; }
            set { _numberA = value; }
        }

        public double NumberB
        {
            get { return _numberB; }
            set { _numberB = value; }
        }

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



    }

然后再次创下造加减乘除类,以便工厂实行调用

class OperationAdd : Operation
    {
        public override double GetResult()
        {
            double result = 0;
            result = NumberA + NumberB;
            return result;
        }
    }

    class OperationSub : Operation
    {
        public override double GetResult()
        {
            double result = 0;
            result = NumberA - NumberB;
            return result;
        }
    }

    class OperationMul : Operation
    {
        public override double GetResult()
        {
            double result = 0;
            result = NumberA * NumberB;
            return result;
        }
    }

    class OperationDiv : Operation
    {
        public override double GetResult()
        {
            double result = 0;
            result = NumberA / NumberB;
            return result;
        }
    }

创设工厂类,实例化出十二分的对象

 public static Operation CreateOperate(string operate)
        {
            Operation oper = null;
            switch (operate)
            {
                case "+":
                    oper = new OperationAdd();
                    break;
                case "-":
                    oper = new OperationSub();
                    break;
                case "*":
                    oper = new OperationMul();
                    break;
                case "/":
                    oper = new OperationDiv();
                    break;

            }
            return oper;
        }

 

经过多态,重返父类的不二等秘书技,然后完毕总计结果

static void Main(string[] args)
        {
            Operation oper;
            oper = OperationFactory.CreateOperate("+");
            oper.NumberA = 1;
            oper.NumberB = 2;
            double result = oper.GetResult();
            Console.WriteLine(result);
            Console.ReadLine();
        }

然而简单工厂格局会存在贰个主题素材,后续假如新扩大方法的话那么还亟需持续开创运算类,然后实例化对象,那么这么会增加代码结构的复杂度,当然还是有法子消除的,可是此地就只做轻松工厂形式的牵线了,

三层模型基本上只要不是用了特地的主意那么基本都以依附轻巧工厂方式来拍卖方法的

相关文章

发表评论

电子邮件地址不会被公开。 必填项已用*标注

*
*
Website