首页 > 代码库 > 简单工厂模式
简单工厂模式
实现一个计算机的功能,可以对两个数进行加、减、剩、除
1、创建一个运算类,让具体的运算去继承
public class Operation
{
private double numberA = 0;
private double numberB = 0;
public double NumberA {
get { return numberA; }
set { numberA = value; }
}
public double NumberB {
get { return numberB; }
set { numberB = value; }
}
public virtual double GetResult() {
double result = 0;
return result;
}
}
2、具体的操作类去继承操作类
//加法类 class OperAdd : Operation { public override double GetResult() { double result = 0; result = NumberA + NumberB; return result; } } //减法类 class OperSub : Operation { public override double GetResult() { double result = 0; result = NumberA - NumberB; return result; } } //剩法类 class OperMul : Operation { public override double GetResult() { double result = 0; result = NumberA * NumberB; return result; } } //除法类 class OperDiv : Operation { public override double GetResult() { double result = 0; return result = NumberA / NumberB; } }
3、简单工厂类,里面有一个创建运算类的方法
//运算工厂类 public class OperationFactory { //创建具体类的静态方法 public static Operation CreateOperation(string str){ Operation oper = null; switch (str) { case "+": oper = new OperAdd(); break; case "-": oper = new OperSub(); break; case "*": oper = new OperMul(); break; case "/": oper = new OperDiv(); break; } return oper; } }
3、客户端代码
static void Main(string[] args) { // 直接通过简单工厂创建运算类 Operation oper = OperationFactory.CreateOperation("+"); oper.NumberA = 8; oper.NumberB = 10; oper.GetResult(); }
简单工厂模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。