C# 设计模式,简单工厂

C# 实现计算机功能 (封装,继承,多态)

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace 简单工厂 {
 8     class Program {
 9         
10         static void Main(string[] args) {
11             Operation op = Facotry.createFactory("+");
12             op.Number1 = 10;
13             op.Number2 = 20;
14             int result = op.getResult();
15             Console.WriteLine(op.ToString());
16             Console.ReadKey();
17         }
18         class Operation { //父类,封装
19             protected int number1;
20             protected int number2;
21 
22             public int Number1 {
23                 get { return number1; }
24                 set { number1 = value; }
25             }
26             public int Number2 {
27                 get { return number2; }
28                 set { number2 = value; }
29             }
30             public virtual int getResult() {
31                 int result = 0;
32                 return result;
33             }
34         }
35         class OperationAdd : Operation {
36             public override int getResult() {
37                 return number1 + number2;
38             }
39         }
40 
41         class OperationSub : Operation {
42             public override int getResult() {
43                 return number1-number2;
44             }
45         }
46         
47         class Facotry {
48             public static Operation createFactory(string ope) {
49                 Operation op = null;
50                 switch (ope) {
51                     case "+":
52                         op = new OperationAdd();
53                         break;
54                     case "-":
55                         op = new OperationSub();
56                         break;
57                 }
58                 return op;
59             }
60         }
61     }
62 }
View Code
原文地址:https://www.cnblogs.com/zgrh/p/11114882.html