简单工厂模式---计算器
一只站在树上的鸟儿,从来不会害怕”树枝”会断裂,因为它相信的不是树枝,而是自己的翅膀。与其每天担心未来,不如努力做好现在。因为,成功的路上,只有奋斗才能给你最大的安全感。
今天写了一个利用面向对象三大特性(封装,继承,多态)以及设计模式实现的计算器程序,使用面向对象特性使代码易维护,易扩展,使用设计模式可以使程序更加灵活,并且易于复用
具体实现代码:
先定义一个运算类
1 //运算类
2 public abstract class Operation
3 {
4 private double numberA;
5
6 public abstract double GetResult();
7
8 public double NumberA
9 {
10 get { return numberA; }
11 set { numberA = value; }
12 }
13 private double numberB;
14
15 public double NumberB
16 {
17 get { return numberB; }
18 set { numberB = value; }
19 }
20
21
22 }
加减乘除类继承运算类
1 //加法类
2 public class OperationAdd:Operation
3 {
4 public override double GetResult()
5 {
6 double result = 0;
7 result=this.NumberA + this.NumberB;
8 return result;
9 }
10 }
11
12
13 //减法类
14 public class OperationSub:Operation
15 {
16 public override double GetResult()
17 {
18 double result = 0;
19 result = this.NumberA - this.NumberB;
20 return result;
21 }
22 }
23
24
25 //乘法类
26 public class OperationMul:Operation
27 {
28 public override double GetResult()
29 {
30 double result = 0;
31 result = this.NumberA * this.NumberB;
32 return result;
33 }
34 }
35
36
37 //除法类
38 public class OperationDiv:Operation
39 {
40 public override double GetResult()
41 {
42 double result = 0;
43 //判断用户输入的除数是非为0
44 if(this.NumberB==0)
45 {
46 //抛出异常,提示用户除数不能为0
47 throw new Exception("除数不能为0!!!");
48 }
49 result = this.NumberA /this.NumberB;
50 return result;
51 }
52 }
工厂类
1 //简单工厂
2 public class OperationFactory
3 {
4 //传入什么符号就实例化那个方法对象
5 public static Operation createOperate(string operate)
6 {
7 Operation ot = null;
8 switch(operate)
9 {
10 case "+":
11 ot = new OperationAdd();
12 break;
13 case "-":
14 ot = new OperationSub();
15 break;
16 case "*":
17 ot = new OperationMul();
18 break;
19 case "/":
20 ot = new OperationDiv();
21 break;
22 default:
23 Console.WriteLine("请输入正确符号:");
24 break;
25 }
26 return ot;
27 }
28 }
客户端(Main方法)
1 static void Main(string[] args)
2 {
3 Console.WriteLine("请输入第一个数:");
4 double numA =Convert.ToDouble(Console.ReadLine());
5 Console.WriteLine("请输入第二个数:");
6 double numB = Convert.ToDouble(Console.ReadLine());
7 Console.WriteLine("请输入运算符号:");
8 string operate = Console.ReadLine();
9 Operation ot = OperationFactory.createOperate(operate);
10 ot.NumberA = numA;
11 ot.NumberB = numB;
12 Console.WriteLine("结果为:"+ot.GetResult());
13 Console.ReadLine();
14 }
使用Java语言现实是大部分都是一样的
希望对你有所帮助!!!