- 总结 abstract
通过调用工厂的公共接口, 以传递参数的低耦合方式创建实例.
作用: 创建实例
特点: 低耦合
Create and return a concrete instance via calling the factory method in the client with one parameter or more, which is a lower coupling way than directly creating instances in client side. - 模型图 UML diagram
- 关键: 解耦 critical: decoupling
高耦合例子, high coupling
//客户端承担了确认运算类型和创建实例两种任务, 且前端必须了解有多少种运算类, 以及类名等信息.
//In client side, when executing one operation, client side need to add a new line responsible for not only operation type but creating instances, so clients must know info of possible operation class like their names.
Operation op = new AddOperation();
op.operate(1.3, 2.7);
Operation op = new SubOperation();
op.operate(1.3, 2.7);
低耦合, low coupling
//客户端承担了确认运算类型, 创建实例交给了公共的工厂方法, 客户端只需要知道工厂方法参数值.
//client chooses the operating type and leaves the instance creating job to the operation factory, it is enough for clients to know just value list of parameters.
Operation operation = OperationFactory.createOperation("+");
operation.operate(1.5, 2.7);
Operation operation = OperationFactory.createOperation("-");
operation.operate(1.5, 2.7);