设计模式——简单工厂模式
本质:
通过传入参数,来获取所需要的对象,不需要了解其中的实现。
Demo:
Java实现计算器。
未使用设计模式的代码:
/** * 计算器的实现(无设计模式) * @author tujietg * */ public class Calculator { public static void main(String[] args) throws Exception { Scanner scanner; System.out.println("输入a:"); scanner = new Scanner(System.in); int a = scanner.nextInt(); System.out.println("输入b:"); scanner = new Scanner(System.in); int b = scanner.nextInt(); System.out.println("输入:sign"); scanner = new Scanner(System.in); String sign = scanner.nextLine(); System.out.println(Operation(a, b, sign)); } public static int Operation(int a, int b, String sign) throws Exception { int sum = 0; switch (sign) { case "+": sum = a + b; break; case "-": sum = a - b; break; case "*": sum = a * b; break; case "/": if (b == 0) { throw new Exception("被除数不能为0"); } sum = a / b; break; } return sum; } }
简单工厂模式结构:
Operation:抽象运算类,所有的运算实现类的父类,包含了抽象的方法。
OperationImpl:继承运算的父类,重写其运算方法,一般是多个类。(加减乘除)
SimpleFactory:简单工厂类的核心,被外界调用,根据传入的参数创建对象。
运算父类代码:
public abstract class Operation { int FirstNum; int SecondNum; public int getFirstNum() { return FirstNum; } public void setFirstNum(int firstNum) { FirstNum = firstNum; } public int getSecondNum() { return SecondNum; } public void setSecondNum(int secondNum) { SecondNum = secondNum; } public abstract int getResult() throws Exception; }
运算父类的实现类:
//加法 class OperationAddImpl extends Operation { @Override public int getResult() { return FirstNum + SecondNum; } } //除法 class OperationDivImpl extends Operation { @Override public int getResult() throws Exception { if (SecondNum == 0) { throw new Exception("被除数不能为0"); } else { return FirstNum / SecondNum; } } } //减法 class OperationSubImpl extends Operation { @Override public int getResult() { return FirstNum - SecondNum; } } //乘法 class OperationMulDivImpl extends Operation { @Override public int getResult() { return FirstNum * SecondNum; } }
简单工厂类:
public class CalcSimFactory { public static Operation getMethod(String sign) { Operation oper = null; switch (sign) { case "+": oper = new OperationAddImpl(); break; case "-": oper = new OperationSubImpl(); break; case "*": oper = new OperationMulDivImpl(); break; case "/": oper = new OperationDivImpl(); break; } return oper; } }
客户端:
public class Client { public static void main(String[] args) throws Exception { Operation oper = CalcSimFactory.getMethod("+"); oper.setFirstNum(10); oper.setSecondNum(2); System.out.println(oper.getResult()); } }
总结:上面的Demo可以看出,客户端通过传入参数调用简单工厂,简单工厂通过参数判断实例化需要的类。
问题:增加新的运算符的时候,会对工厂类进行修改编译,违背了开闭原则。
特性:将对象的创建和对象本身业务处理分离可以降低系统的耦合度,使得两者修改起来都相对容易。