工厂模式简单运用
2013-06-10 08:04
344 查看
运用工厂模式实现简单计算
输出结果为:
输入第一个数:
3
输入运算符:
+
输入第二个数:
2
运算结果为:5
package com.product4; /** * 抽象的运算类,包括操作数 * @author Owner * */ public abstract class Operation { private int num1; private int num2; /** * 运算结果的抽象方法 * @return */ public abstract int getResult(); public int getNum1() { return num1; } public void setNum1(int num1) { this.num1 = num1; } public int getNum2() { return num2; } public void setNum2(int num2) { this.num2 = num2; } }
package com.product4; /** * 加运算类,实现getResult获取加后的结果 * @author Owner * */ public class AddOperation extends Operation{ @Override public int getResult() { return this.getNum1() + this.getNum2(); } }
package com.product4; /** * 减运算类,实现具体的减操作运算 * @author Owner * */ public class SubtractOperation extends Operation{ @Override public int getResult() { return this.getNum1() - this.getNum2(); } }
package com.product4; /** * 运算的工厂类,主要生成加/减操作对象 * @author Owner * */ public class OperationFactory { /** * 通过操作符号,获取运算对象 * @param oper * @return */ public static Operation getOperation(String oper){ if(oper.equals("+")){ return new AddOperation(); }else if(oper.equals("-")){ return new SubtractOperation(); }else{ return null; } } }
package com.product4; import java.util.Scanner; /** * * @author Owner * */ public class Customer { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("输入第一个数:"); int num1 = sc.nextInt(); System.out.println("输入运算符:"); String oper = sc.next(); System.out.println("输入第二个数:"); int num2 = sc.nextInt(); //获取运算对象 Operation operation = OperationFactory.getOperation(oper); operation.setNum1(num1); operation.setNum2(num2); System.out.println("运算结果为:"+operation.getResult()); } }
输出结果为:
输入第一个数:
3
输入运算符:
+
输入第二个数:
2
运算结果为:5
相关文章推荐
- Java 工厂模式简单运用
- mybatis简单运用(基于Annotation)
- FileUpload上传组件在ASP.net中最简单的运用示例
- 流的简单运用(以txt格式输出)
- Python Django 学习笔记 Python简单运用(二)
- windows服务 MVC之@Html.Raw()用法 文件流的读写 简单工厂和工厂模式对比
- wireshark简单运用笔记(二)
- Java基础---Java---基础加强---内省的简单运用、注解的定义与反射调用、 自定义注解及其应用、泛型及泛型的高级应用、泛型集合的综合
- CSS教程(八) 简单介绍CSS结合JS的运用
- csla简单多层系统中使用工厂模式操作 readonlylistbase
- html导航栏-简单运用display设置左拉和下拉导航栏
- 一、ios的通过Xib构建UICollectionView的简单运用
- DispatchTouchEvent的简单运用
- 运用js简单制作图片的左右移动
- map_reduce的简单运用
- Python3.6 连接mysql 数据库,增删改查,及多线程简单运用
- 汇编语言中编写子程序的标准框架及简单运用举例
- 第三单元man指令的简单运用
- 【23种设计模式】创建型模式 > 三个工厂模式(简单工厂、抽象工厂、工厂方法)
- A*算法的简单运用