码迷,mamicode.com
首页 > 其他好文 > 详细

简单工厂设计模式

时间:2018-10-17 18:30:04      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:oid   line   main   col   read   ogr   key   factor   模式   

一、操作类

  

 1     public class Operation
 2     {
 3         public double _numberA = 0;
 4         public double _numberB = 0;
 5         public double NumberA
 6         {
 7             get { return _numberA; }
 8             set { _numberA = value; }
 9         }
10         public double NumberB
11         {
12             get { return _numberB; }
13             set { _numberB = value; }
14         }
15         public virtual double GetResult()
16         {
17             return 0;
18         }
19     }

 

二、具体操作类

  

1     public class OperationAdd : Operation
2     {
3         public override double GetResult()
4         {
5             return NumberA + NumberB;
6         }
7     }
1  public class OperationSub : Operation
2     {
3         public override double GetResult()
4         {
5             return NumberA - NumberB;
6         }
7     }

 

 

三、工厂类

  

 1   public class OperationFactory
 2     {
 3         public static Operation CreateOperate(string type)
 4         {
 5             Operation oper = null;
 6             switch (type)
 7             {
 8                 case "+":
 9                     oper = new OperationAdd();
10                     break;
11                 case "-":
12                     oper = new OperationSub();
13                     break;
14                 default:
15                     break;
16             }
17             return oper;
18         }
19     }

 

 

四、测试

  

 1  class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             Operation op;
 6             op = OperationFactory.CreateOperate("+");
 7             op.NumberA = 1;
 8             op.NumberB = 2;
 9             Console.WriteLine(op.GetResult());
10             Console.WriteLine("__________________");
11             op = OperationFactory.CreateOperate("-");
12             op.NumberA = 5;
13             op.NumberB = 3;
14             Console.WriteLine(op.GetResult());
15             Console.ReadKey();
16         }
17     }

 

简单工厂设计模式

标签:oid   line   main   col   read   ogr   key   factor   模式   

原文地址:https://www.cnblogs.com/hyunbar/p/9805938.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!