大话设计模式之 工厂模式

//被继承类  

public class operate
    {

        private double _num1;
        private double _num2;
        private double sum=0;
        public double Num1
        {
            get {
                return _num1;
            }
            set {
                _num1 = value;
            }
        }
        public double Num2
        {
            get
            {
                return _num2;
            }
            set
            {
                _num2 = value;
            }
        }
        public virtual double GetSum()
        {
            return sum;
        }
    }
    public class oprAdd:operate
    {
        public override double GetSum()
        {
            return Num1 + Num2;
        }
    }
    public class oprSub : operate
    {
        public override double GetSum()
        {
            return Num1 - Num2;
        }
    }

    class oprFactory
    {
        public operate CreateOpr(string symbol)
        {
            operate objoperate=null;
            switch (symbol)
            {
                case "+":
                    objoperate = new oprAdd();
                    break;
                case "-":
                    objoperate = new oprSub();
                    break;
                default:
                    break;
           
            }
            return objoperate;
        }
    }

 

//调用

         private void button4_Click(object sender, EventArgs e)
        {
            oprFactory a = new oprFactory();
            operate op = a.CreateOpr("+");
            op.Num1 = 100;
            op.Num2 = 20;
            MessageBox.Show( op.GetSum().ToString());
           
        }

工厂模式:根据输入的参数,建立相应的对象,这样有利于扩充,如果以后对功能进行扩充,我们只要修改我们要添加的功能,而不去动过去的代码,避免发生意外。

你可能感兴趣的:(设计模式,object,String,null,Class,button)