设计模式之简单工厂
来源:互联网 发布:php 去除数组重复元素 编辑:程序博客网 时间:2024/06/09 22:12
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApplication1{ class Program { static void Main(string[] args) { Operation oper; oper = OperationFactory.createOperate("+"); oper.NumberA = 1; oper.NumberB = 2; double result = oper.GetResult(); } } public class Operation { private double _numberA; private double _numberB; 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; } } public class OperationAdd : Operation { public override double GetResult() { double result = 0; result = NumberA + NumberB; return result; } } public class OperationSub : Operation { public override double GetResult() { double result = 0; result = NumberA - NumberB; return result; } } public class OperationMul : Operation { public override double GetResult() { double result = 0; result = NumberA * NumberB; return result; } } public class OperationDiv : Operation { public override double GetResult() { double result = 0; if (NumberB == 0) throw new Exception("除数不能为0。"); result=NumberA/NumberB; return result; } } public class OperationFactory { public static Operation createOperate(string operation) { Operation oper=null; switch(operation) { case "+": oper=new OperationAdd(); break; case "-": oper=new OperationSub(); break; case "*": oper=new OperationMul(); break; case "/": oper=new OperationDiv(); break; } return oper; } }}
工厂 OperationFactory:
方法createOperation是Operation类型,定义了一个Operation类型的变量oper,
根据operation:"+"、"-"、"*"、"/",实例化(继承父类Operation)OperationAdd、OperationSub、OperationMul、OperationDiv
oper=new OperationAdd();
客户端:
定义Operation类型的变量oper;
oper = OperationFactory.createOperate("+");
决定oper实例化OperationAdd,
double result = oper.GetResult();
直接调OperationAdd的GetResult方法:
public class OperationAdd : Operation
{
public override double GetResult()
{
double result = 0;
result = NumberA + NumberB;
return result;
}
}
0 0
- 设计模式 之简单工厂+ 工厂模式
- 设计模式 之 简单工厂
- 设计模式之简单工厂
- 设计模式之简单工厂
- 设计模式之简单工厂
- 设计模式之简单工厂
- 设计模式之简单工厂
- 设计模式之简单工厂
- 设计模式之简单工厂
- 设计模式之简单工厂
- 设计模式之简单工厂.
- 设计模式之简单工厂
- 设计模式之简单工厂
- 设计模式之简单工厂
- 设计模式之简单工厂
- 设计模式之简单工厂
- 设计模式之简单工厂
- 设计模式之简单工厂
- 二叉排序树
- 源码推荐:保存app内容到手机桌面,类AppStore横向滚动
- 阶乘因式分解(一)
- Android应用开发人员的10个建议
- vi常用命令
- 设计模式之简单工厂
- 黑马程序员Java基础第七章-----单例设计模式,异常
- C#探秘系列(五)
- 34. PHP 执行运算符
- MyBatis实用教程
- 【概率DP】 ZOJ 2949 Coins of Luck 期望
- 第10题:翻转句子中单词的顺序
- Google推荐的图片加载库Glide介绍
- [HNOI2004]打鼹鼠 解题报告