面向编程对象的好处及应用封装(1-1)

面向编程对象的好处及应用封装(1-1)

  1. 当初:
    • 自己的代码有时候做到一半发现之前有些过这些类似的只是小部分地方不同,用复制粘贴改改就可以继续用了
    • 当初只要是实现功能就行了,需要要是再改变就很麻烦一个两个地方还能承受多了的话会吃不消
  2. 现在:
    • 这样的话就考虑通过封装,继承,多态把程序的耦合度 (是指一程序中,模块及模块之间信息或参数依赖的程度) 降低。
    • 用设计模式使得程序员变得灵活,容易修改和复用了。

可以参考之前的 计算器随笔做比较

Operation运算类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DesignModel
{
   public class Operation
{
#region Operation运算类

 
public static double GetResult(double numberA,double numberB,string operate)
{
double result = 0d;//d表示双精度浮点数
switch (operate)
{
case "+":
result = numberA + numberB;
break;
case "-":
result = numberA - numberB;
break;
case "*":
result = numberA * numberB;
break;
case "/":
//三目运算
numberB = numberB != 0 ? result =numberA / numberB  : result = 0;//除数不能为0,否则就等于0
break;
}
return result;
}
   #endregion
}
}

计算器客户端类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DesignModel
{
   public class Program
{
   public static void Main(string[] args)
{
#region  计算器客户端类

try
{
Console.WriteLine("请输入数字A:");
string NumberA = Console.ReadLine();
Console.WriteLine("请选择运算(+ - * /)");
string strOption = Console.ReadLine();
  Console.WriteLine("请输入数字B:");
string NumberB = Console.ReadLine();
//调用之前写的 Operation 运算类
string Result = Convert.ToString(Operation.GetResult(Convert.ToDouble(NumberA),Convert.ToDouble(NumberB),strOption));

Console.WriteLine("结果是:"+Result);
Console.ReadLine();

}
catch (Exception ex)
{

Console.WriteLine(ex);
}
#endregion

}
}
}

总结
面向对象三大特性之一 封装

这是把业务和界面分离了,可以复用Operation类,这是面向对象的封装及应用,之后会更新面向对象的继承和多态

猜你喜欢

转载自www.cnblogs.com/zaohuojian/p/11483963.html