标签:简单工厂模式
简单工厂模式实现计算器,UML图例如下:
1、用例图
2、类图
3、顺序图
4、活动图
简单代码如下(eclipse代码打包在附件里):
import java.util.Scanner; abstract class Operator { private double opA; private double opB; public double getOpA() { return opA; } public void setOpA(double opA) { this.opA = opA; } public double getOpB() { return opB; } public void setOpB(double opB) { this.opB = opB; } public abstract void operator(); } class OperatorAdd extends Operator{ //由于加法一定要有两个参数,因此就直接不提供无参数构造方法了 public OperatorAdd(double opA,double opB){ this.setOpA(opA); this.setOpB(opB); } @Override public void operator() { System.out.println(this.getOpA()+" + "+this.getOpB()+" = "+(this.getOpA()+this.getOpB())); } } class OperatorSub extends Operator{ public OperatorSub(double opA,double opB){ this.setOpA(opA); this.setOpB(opB); } @Override public void operator() { System.out.println(this.getOpA()+" - "+this.getOpB()+" = "+(this.getOpA()-this.getOpB())); } } class OperatorMul extends Operator{ public OperatorMul(double opA,double opB){ this.setOpA(opA); this.setOpB(opB); } @Override public void operator() { System.out.println(this.getOpA()+" * "+this.getOpB()+" = "+(this.getOpA()*this.getOpB())); } } class OperatorDiv extends Operator { public OperatorDiv(double opA,double opB){ this.setOpA(opA); this.setOpB(opB); } @Override public void operator() { try { if(this.getOpB()==0){ throw new Exception(); } double result = this.getOpA()/this.getOpB(); System.out.println(this.getOpA()+" / "+this.getOpB()+" = "+result); } catch (Exception e) { System.out.println("error-----除数不能为0"); } } } //工厂类 class OperatorFactory { public static Operator getNewOperator(double opA,double opB,char ch){ switch (ch) { case ‘+‘: return new OperatorAdd(opA, opB); case ‘-‘: return new OperatorSub(opA, opB); case ‘*‘: return new OperatorMul(opA, opB); case ‘/‘: return new OperatorDiv(opA, opB); default: break; } return null; } } //程序入口 class Main { public static void main(String[] args) { @SuppressWarnings("resource") Scanner input = new Scanner(System.in); System.out.println("请输入操作数opA:"); double opA=input.nextDouble(); System.out.println("请输入操作数opB:"); double opB = input.nextDouble(); System.out.println("请输入运算符:"); char ch = input.next().charAt(0); Operator operator = OperatorFactory.getNewOperator(opA, opB, ch); operator.operator(); } }
本文出自 “夕下等花逝” 博客,请务必保留此出处http://sunshine2624.blog.51cto.com/3959438/1876999
标签:简单工厂模式
原文地址:http://sunshine2624.blog.51cto.com/3959438/1876999