工廠模式(Factory Pattern):javascript
定義:定義一個建立對象的接口,但讓實現這個接口的類來決定實例化哪一個類。工廠方法讓類的實例化推遲到子類中進行。
目的:工廠模式是爲了解耦,把對象的建立和使用的過程分開。
場景:須要生成複雜對象,須要下降耦合度的場景。
例子:JS代碼實現 java
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 } }