首页 > 代码库 > 简单工厂模式实例
简单工厂模式实例
运算类
public class operation { private double a = 0; private double b = 0; public double A { get { return a; } set { a = value; } } public double B { get { return b; } set { b = value; } } public virtual double GetResult() { double rst = 0; return rst; } }
加减乘除类
public class Jia : operation { public override double GetResult() { double result = 0; result = A + B; return result; } } public class Jian : operation { public override double GetResult() { double result = 0; result = A - B; return result; } } public class Cheng : operation { public override double GetResult() { double result = 0; result = A * B; return result; } } public class Chu : operation { public override double GetResult() { double result = 0; if(B==0) throw new Exception("除数不能为0"); result = A / B; return result; } }
工厂类
public class OperationFactory { public static operation CreateOperation(string operation) { operation result = null; switch (operation) { case "+": result = new Jia(); break; case "-": result = new Jian(); break; case "*": result = new Cheng(); break; case "/": result = new Chu(); break; default: break; } return result; } }
控制台请求
Console.Write("请输入第一个数"); double a =Convert.ToDouble(Console.ReadLine()); Console.Write("请输入第二个数"); double b =Convert.ToDouble(Console.ReadLine()); Console.Write("请输入运算符"); string opr = Console.ReadLine(); operation opr2 = OperationFactory.CreateOperation(opr); opr2.A = a; opr2.B = b; double result = opr2.GetResult(); Console.WriteLine(result); Console.ReadLine();
简单工厂模式实例
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。