简单工厂模式,其实就是有一个静态的工厂方法,可以根据输出的条件返回对应的实例,然后再条用具体的实例的方法执行计算。
简单工厂模式相当与将条件判断都集中到了一个静态的工厂方法中。这样的好处是,执行具体计算任务的代码不需要再有很多的if判断,只专注于具体的计算。如果有新的计算需求,那么只需要增加相应的计算方法,并且在工厂方法中添加对应的入口条件就行了,对原有的计算方法没有任何影响。
一个简单计算器的实现例子如下
计算的类型接口:
/** * @author wgyang * Create time: 2020-04-04 15:34 * Description: */ public interface Operator { /** * 计算 * * @param number1 数字1 * @param number2 数字2 * @return 返回计算的结果 */ String calculate (int number1, int number2); }
四则运算操作:
/** * @author wgyang * Create time: 2020-04-04 15:44 * Description: 加法操作 */ public class OperatorAdd implements Operator { public String calculate(int number1, int number2) { return String.valueOf(number1 + number2); } }
/** * @author wgyang * Create time: 2020-04-04 15:48 * Description: 减法操作 */ public class OperatorSubtraction implements Operator { public String calculate(int number1, int number2) { return String.valueOf(number1 - number2); } }
/** * @author wgyang * Create time: 2020-04-04 15:49 * Description: 乘法操作 */ public class OperatorMultiplication implements Operator { public String calculate(int number1, int number2) { return String.valueOf(number1 * number2); } }
/** * @author wgyang * Create time: 2020-04-04 15:50 * Description: 出发操作 */ public class OperatorDivision implements Operator { public String calculate(int number1, int number2) { if (number2 == 0) { return "除数不能为0"; } else { return String.valueOf(number1 / number2); } } }
静态工厂类:
/** * @author wgyang * Create time: 2020-04-04 15:56 * Description: 操作的工厂类 */ public class OperatorFactory { public static Operator createOperator(String operate) { switch (operate) { case "+": return new OperatorAdd(); case "-": return new OperatorSubtraction(); case "*": return new OperatorMultiplication(); case "/": return new OperatorDivision(); default: throw new UnsupportedOperationException(String.format("不支持的操作类型:%s", operate)); } } }
计算器类:
/** * @author wgyang * Create time: 2020-04-04 15:32 * Description: 实现一个简单的计算器,输入两个整数,对其进行加、减、乘、除运算,运用简单工厂设计模式 */ public class Calculator { public static void main(String[] args) { int number1 = 2; int number2 = 5; Operator operator = OperatorFactory.createOperator("+"); System.out.println(operator.calculate(number1, number2)); Operator operator1 = OperatorFactory.createOperator("-"); System.out.println(operator1.calculate(number1, number2)); Operator operator2 = OperatorFactory.createOperator("*"); System.out.println(operator2.calculate(number1, number2)); Operator operator3 = OperatorFactory.createOperator("/"); System.out.println(operator3.calculate(number1, number2)); Operator operator4 = OperatorFactory.createOperator("%"); System.out.println(operator4.calculate(number1, number2)); } }
该例子中只实现了计算器的加减乘除四则运算,如果要新增乘方,开方等运算,只需要实现Operator接口,并在createOperator()方法中添加相应的入口即可,对原有的加减乘除的实现不会产生任何影响。
来源:https://www.cnblogs.com/wgyang/p/12632682.html