一、简单工厂模式:
实质是由一个工厂类根据传入的参数,动态决定应该创建哪一个产品类(这些产品类继承自一个父类或接口)的实例。简单工厂模式的创建目标,所有创建的对象都是充当这个角色的某个具体类的实例。
二、场景
使用Java面向对象语言实现一个计算机控制台程序,要求输入两个数和运算符号,得到结果。
为了使程序达到易扩展,易维护,易复用且灵活的目的,本程序将使用到面向对象编程思想的三大特性:封装、继承和多态,以及简单工厂模式
三、程序代码
程序共有七个类:
MyOperation.java
public class MyOperation { private double numberA; private double numberB; public double getNumberA() { return numberA; } public void setNumberA(double numberA) { this.numberA = numberA; } public double getNumberB() { return numberB; } public void setNumberB(double numberB) { this.numberB = numberB; } public double getResult() throws Exception { double result=0; return result; } }
OperaAdd.java
public class OperaDiv extends MyOperation{ @Override public double getResult() throws Exception { if(this.getNumberB()==0){ throw new Exception("除数不能为0"); } return this.getNumberA()/this.getNumberB(); } }
OperaSub.java
public class OperaDiv extends MyOperation{ @Override public double getResult() throws Exception { if(this.getNumberB()==0){ throw new Exception("除数不能为0"); } return this.getNumberA()/this.getNumberB(); } }
OperaMul.java
public class OperaDiv extends MyOperation{ @Override public double getResult() throws Exception { if(this.getNumberB()==0){ throw new Exception("除数不能为0"); } return this.getNumberA()/this.getNumberB(); } }
OperaDiv.java
public class OperaDiv extends MyOperation{ @Override public double getResult() throws Exception { if(this.getNumberB()==0){ throw new Exception("除数不能为0"); } return this.getNumberA()/this.getNumberB(); } }
OperationFactory.java
public class OperationFactory { public static MyOperation createOperation(String operate){ MyOperation operation=null; switch (operate) { case "+": operation=new OperaAdd(); break; case "-": operation=new OperaSub(); break; case "*": operation=new OperaMul(); break; case "/": operation=new OperaDiv(); break; default: operation=new MyOperation(); break; } return operation; } }
Calculator.java
import java.util.Scanner;public class Calculator { /** * @Title: main * @Description: 计算器 * @param args * @return void 返回类型 * @throws */ public static void main(String[] args) { MyOperation operation=null; try { System.out.println("请输入数字A:"); double numberA=Double.valueOf(new Scanner(System.in).nextLine()); System.out.println("请输入运算符:"); String operaString=new Scanner(System.in).nextLine(); System.out.println("请输入数字B:"); double numberB=Double.valueOf(new Scanner(System.in).nextLine()); operation=OperationFactory.createOperation(operaString); operation.setNumberA(numberA); operation.setNumberB(numberB); System.out.println("结果是:"+operation.getResult()); } catch (NumberFormatException e) { System.out.println("只能输入数字"); } catch (Exception e) { System.out.println(e.getMessage()); } } }