近讀《大話模式設計》一書,更感感受本身對軟件設計方面一竅不通,實在是個「碼農」。功過此書對軟件工程等方面的基礎知識有個簡單的瞭解,在此將我的理解整理,備案。java
簡單工廠模式又稱爲靜態工廠模式,是由一個工廠對象來肯定具體實例化哪一個產品實例。用戶只需傳入條件,工廠根據條件返回符合要求的產品實例。
ide
例子:this
根據用戶的選擇,進行加、減、乘、除運算。若是按照我原來的code習慣,應該是:設計
if ("+") { //沒有任何返利 } if ("-"){ // } if ("*") { // }
此處的毛病就是對用戶的一個狀態,代碼要進行屢次判斷,並且每次返回不一樣的數據都會徹底暴露給用戶,沒有作好數據的封裝。若是:code
switch("四則運算"){ case "+": ... break; case "-": ... break; case "*": ... break; ... }
則會避免數據外泄。而且易於擴展。對象
實例:get
//全部操做類的父類 public abstract class Operation { public Operation() { } 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(); private double numA = 0; private double numB = 0; } /** * 加法類 * */ class OperationAdd extends Operation { public OperationAdd() { super(); } @Override public double getResult() { return (getNumA() + getNumB()); } } /** * 減法類 * */ class OperationSub extends Operation { public OperationSub() { super(); } @Override public double getResult() { return (getNumA() - getNumB()); } } /** * 乘法類 * */ class OperationMul extends Operation { public OperationMul() { super(); } @Override public double getResult() { return (getNumA() * getNumB()); } } /** * 除法類,當除數爲0時,返回值爲0 * */ class OperationDiv extends Operation { public OperationDiv() { super(); } public double getResult() { if (getNumB() != 0) { return (getNumA() / getNumB()); } else { return 0; } } }
四則運算的標誌集合:
產品
enum OperatorCollection { ADD, SUB, MUL, DIV }
具體工廠類:it
public class OperationFactory { public static Operation createFactory(OperatorCollection oc) { Operation op = null; switch (oc) { case ADD: op = new OperationAdd(); break; case SUB: op = new OperationSub(); break; case MUL: op = new OperationMul(); break; case DIV: op = new OperationDiv(); break; } return op; } private OperationFactory() { } }
main類:io
public class ClientClass { public static void main(String[] args) { new ClientClass().operationFunction(20, 33, OperatorCollection.MUL); } private void operationFunction(double numA, double numB, OperatorCollection oc) { Operation op = OperationFactory.createFactory(oc); op.setNumA(numA); op.setNumB(numB); String operator = ""; switch (oc) { case ADD: operator = " + "; break; case SUB: operator = " - "; break; case MUL: operator = " * "; break; case DIV: operator = " / "; break; } System.out.println(numA + operator + numB + " = " + op.getResult()); } }
只要輸入數字和運算符號,直接就能夠進行計算,並且數據也可封裝。