简单工厂模式是当有许多个功能类似的类时,为了隔离客户端代码直接操作这些不同的类,在客户端与多个类中间使用一个工厂类,封装掉这些类的不确定性,给客户端代码提供一个一致的接口。
也就是说,工厂类按照输入的参数,构造一个合适的类返回给客户端。客户端通过父类(或接口)调用。
举一个简单的例子来说,我们要实现一个有加减乘除功能的计算器,由用户输入+ - * /和两个数字,打印计算结果。
在这里,加减乘除是四个功能类似的类,完成的任务都是对两个操作数执行某种运算,然后打印结果。
来看一下UML图:
核心思想在于让不同的操作继承同一个基类Operation,然后各自实现getResult方法。OperationFactory类通过输入参数,返回特定的子类,客户端调用getResult方法。
来看代码,Operation及其子类:
public abstract class Operation { private double numA = 0; private double numB = 0; public double getNumA() { return numA; } public void setNumA(double numA) { this.numA = numA; } public double getNumB() { return numB; } public void setNumB(double numB) { this.numB = numB; } public abstract double getResult(); } public class OperationAdd extends Operation { @Override public double getResult() { return getNumA() + getNumB(); } } public class OperationSub extends Operation { @Override public double getResult() { return getNumA() - getNumB(); } } public class OperationMul extends Operation { @Override public double getResult() { return getNumA() * getNumB(); } } public class OperationDiv extends Operation { @Override public double getResult() { return getNumA() / getNumB(); } }
OperationFactory类:
public class OperationFactory { public static Operation createOperation(String operation) { Operation oper = null; switch (operation) { case "+": oper = new OperationAdd(); break; case "-": oper = new OperationSub(); break; case "*": oper = new OperationMul(); break; case "/": oper = new OperationDiv(); break; default: throw new IllegalArgumentException ("Unsupport operation!"); } return oper; } }
客户端SimpleFactoryDemo类:
public class SimpleFactoryDemo { public static void main(String[] args) { if(args.length == 0){ System.out.println("Usage: java StrategyDemo operation num1 num2"); return; } Operation operation = OperationFactory.createOperation(args[0]); operation.setNumA(Double.parseDouble(args[1])); operation.setNumB(Double.parseDouble(args[2])); double result = operation.getResult(); System.out.println(result); } }
时间: 2024-11-08 15:11:35