工厂模式(Factory Pattern):
定义:定义一个创建对象的接口,但让实现这个接口的类来决定实例化哪个类。工厂方法让类的实例化推迟到子类中进行。
目的:工厂模式是为了解耦,把对象的创建和使用的过程分开。
场景:需要生成复杂对象,需要降低耦合度的场景。
例子:JS代码实现
let operationFactory = { createOperate (operate) { let oper = null switch (operate) { case '+': oper = new operationFactory.OperationAdd() break case '-': oper = new operationFactory.OperationSub() break case '*': oper = new operationFactory.OperationMul() break case '/': oper = new operationFactory.OperationDiv() break } }, OperationAdd () { // TODO run the addition operation }, OperationSub () { // TODO run the subtraction operation }, OperationMul () { // TODO run the multiplication operation }, OperationDiv () { // TODO run the division operation } }