首页 > 代码库 > 简单工厂模式
简单工厂模式
1. 简介
从设计模式的类型上来说,简单工厂模式是属于创建型模式,又叫做静态工厂方法(Static Factory Method)模式,但不属于23种GOF设计模式之一。简单工厂模式是由一个工厂对象决定创建出哪一种产品类的实例。简单工厂模式是工厂模式家族中最简单实用的模式,可以理解为是不同工厂模式的一个特殊实现。
2. 代码示例
1 //运算类 2 public class Operation 3 { 4 private double numberA = 0; 5 private double numberB = 0; 6 7 public double NumberA 8 { 9 get { return numberA; }10 set { numberA = value; }11 } 12 13 public double NumberB14 {15 get { return numberB; }16 set { numberB = value; }17 }18 19 public virtual double GetResult()20 {21 double result = 0;22 return result;23 }24 }25 //加减乘除类26 class OperationAdd:Operation27 {28 public override double GetResult()29 {30 double result = 0;31 result = NumberA + NumberB;32 return result;33 }34 }35 class OperationSub:Operation36 {37 public override double GetResult()38 {39 double result = 0;40 result = NumberA - NumberB;41 return result;42 }43 }44 class OperationMul:Operation45 {46 public override double GetResult()47 {48 double result = 0;49 result = NumberA * NumberB;50 return result;51 }52 }53 class OperationDiv:Operation54 {55 public override double GetResult()56 {57 double result = 0;58 if (NumberB == 0)59 throw new Exception("除数不能为零");60 result = NumberA / NumberB;61 return result;62 }63 }64 //简单运算工厂类65 public class OperationFactory66 {67 public static Operation createOprate(string operate)68 {69 Operation oper = null;70 switch (operate)71 {72 case "+":73 oper = new OperationAdd();74 break;75 case "-":76 oper = new OperationSub();77 break;78 case "*":79 oper = new OperationMul();80 break;81 case "/":82 oper = new OperationDiv();83 break;84 }85 return oper;86 }87 }88 //Main89 static void Main(string[] args)90 {91 Operation oper;92 oper = OperationFactory.createOprate("+");93 oper.NumberA = 1;94 oper.NumberB = 2;95 double result = oper.GetResult();96 97 Console.ReadKey();98 }
简单工厂模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。