1. 概念
简单工厂模式:创建对象工厂(用于生产对象),根据传入条件返回不同的对象
2.案例
本案例以计算器为例,主要实现逻辑有如下几步:
1.根据用户传入的运算符,获取所需要的运算对象
2.根据获得的运算对像调用计算方法
-
创建计算对象父类
public interface Arithmetic { double calute(double arg1,double arg2); }
-
创建各计算对象子类
//加法 public class Plus implements Arithmetic { @Override public double calute(double arg1, double arg2) { return arg1 + arg2; } } //减法 public class Substruction implements Arithmetic { @Override public double calute(double arg1, double arg2) { return arg1 - arg2; } } //乘法 public class Multiplication implements Arithmetic { @Override public double calute(double arg1, double arg2) { return arg1 * arg2; } } //除法 public class Division implements Arithmetic { @Override public double calute(double arg1, double arg2) { if (0==arg2){ throw new RuntimeException("除数不能为0"); } return arg1 / arg2; } }
-
创建计算对象工厂,根据条件返回不同的对象
public class ArithmeticFactory { public static Arithmetic getArithmetic(String operator){ switch (operator){ case "+": return new Plus(); case "-": return new Substruction(); case "*": return new Multiplication(); case "/": return new Division(); default: throw new RuntimeException("输入运算符有误"); } } }
-
验证
public class MainTest { public static void main(String[] args) { Arithmetic plus = ArithmeticFactory.getArithmetic("+"); double calute = plus.calute(1, 2); System.out.println(calute); Arithmetic division = ArithmeticFactory.getArithmetic("/"); calute = division.calute(1, 0); System.out.println(calute); } }
-
案例结构
为了方便理解,如下为本案例结构图: