工做以後,一直忙於工做,像一位前輩所說的那樣,個人確須要好好總結一下所學所用過的知識了。git
就從複習設計模式開始,今天覆習的是簡單工廠設計模式。設計模式
如設計一個簡單的計算器程序:ide
須要從Console端得到兩個數字、一個運算符(+-*/),並計算得出結果。this
此處可利用簡單工廠根據運算符生成運算類,類圖以下:spa
package sf.simpleFactory; import sf.simpleFactory.Operator.DivisionOperator; import sf.simpleFactory.Operator.MinusOperator; import sf.simpleFactory.Operator.MultipleOperator; import sf.simpleFactory.Operator.PlusOperator; public class OperatorFactory { public static Operator getInstance(int digit1, int digit2, String operator) { if (operator.equals("+")) { return new PlusOperator(digit1, digit2, operator); } else if (operator.equals("-")) { return new MinusOperator(digit1, digit2, operator); } else if (operator.equals("*")) { return new MultipleOperator(digit1, digit2, operator); } else if (operator.equals("/")) { return new DivisionOperator(digit1, digit2, operator); } else { return null; } } }
package sf.simpleFactory; public abstract class Operator { public int digit1; public int digit2; public Operator(int digit1, int digit2, String operator) { this.digit1 = digit1; this.digit2 = digit2; } public abstract float calculate(); public static class PlusOperator extends Operator{ public PlusOperator(int digit1, int digit2, String operator) { super(digit1, digit2, operator); } @Override public float calculate() { return digit1 + digit2; } } public static class MinusOperator extends Operator{ public MinusOperator(int digit1, int digit2, String operator) { super(digit1, digit2, operator); } @Override public float calculate() { return digit1 - digit2; } } public static class MultipleOperator extends Operator{ public MultipleOperator(int digit1, int digit2, String operator) { super(digit1, digit2, operator); } @Override public float calculate() { return digit1 * digit2; } } public static class DivisionOperator extends Operator{ public DivisionOperator(int digit1, int digit2, String operator) { super(digit1, digit2, operator); } @Override public float calculate() { return digit1 / digit2; } } }