工厂模式(Factory Pattern):
1 2 3 |
定义:定义一个创建对象的接口,但让实现这个接口的类来决定实例化哪个类。工厂方法让类的实例化推迟到子类中进行。 目的:工厂模式是为了解耦,把对象的创建和使用的过程分开。 场景:需要生成复杂对象,需要降低耦合度的场景。 |
例:JS代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
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 } } |
Github地址:https://github.com/skillnull/[……]