关于计算器的封装

封装代码

  interface chapter
    {
        int answer { get; }



    }

    class Charp : chapter
    {
        private int x1;
        private int x2;
        private string Operator;
        public int result;
        public Charp(int x1, int x2, string Operator)
        {
            this.x1 = x1;
            this.x2 = x2;
            this.Operator = Operator;
       

        }
        public int answer
        {
            get {

                if (Operator == "+")
                {
                    result = x1 + x2;

                }
                if (Operator == "-")
                {

                    result = x1 - x2;

                }
                if (Operator == "*")
                {

                    result = x1 * x2;

                }
                 if (Operator == "/")
                {

                    result = x1 / x2;

                }
                return result;
            }

        

        }

    }

}

调用

  Class3 n = new Class3();
               n.cc();
               first.Text =n.ll[oppo];
               two.Text = n.llp[oppo];
                xx.Text=n.lli[oppo];

                Charp a = new Charp(int.Parse(first.Text), int.Parse(two.Text), xx.Text);
            
                    
                    if (results.Text==Convert.ToString(a.answer))
                    {



                        MessageBox.Show("回答正确");
                        
                      



                    }
                    else
                    {

                        MessageBox.Show("回答错误");
                    }

  

总结

这就是我封装的代码,把计算的算法封装起来了,至于陈老师所说的了策略型模式,就是一个多态的用法,而这个计算器的算法,我感觉用一个普通的类就可以实现。我看了别人的有的使用方法什么的,反正我就是用一个接口继承过来然后直接返回值了。对于老师讲的设计模式,我感觉也是一种多态的表现,在而工厂模式,各种模式就是多态的各种类,在面对不同情况使用不同的设计模式是不是也是面向对象的一种体现,对于封装,我现在最大的感觉就结构清楚了代码没有那么繁琐,条理更加清楚了。革命尚未成功,我们仍需努力

原文地址:https://www.cnblogs.com/fei2/p/4989742.html