1. 概念
簡單工廠模式:創建對象工廠(用於生產對象),根據傳入條件返回不同的對象
2.案例
本案例以計算器爲例,主要實現邏輯有如下幾步:
1.根據用戶傳入的運算符,獲取所需要的運算對象
2.根據獲得的運算對像調用計算方法
-
創建計算對象父類
public interface Arithmetic { double calute(double arg1,double arg2); }
-
創建各計算對象子類
//加法 public class Plus implements Arithmetic { @Override public double calute(double arg1, double arg2) { return arg1 + arg2; } } //減法 public class Substruction implements Arithmetic { @Override public double calute(double arg1, double arg2) { return arg1 - arg2; } } //乘法 public class Multiplication implements Arithmetic { @Override public double calute(double arg1, double arg2) { return arg1 * arg2; } } //除法 public class Division implements Arithmetic { @Override public double calute(double arg1, double arg2) { if (0==arg2){ throw new RuntimeException("除數不能爲0"); } return arg1 / arg2; } }
-
創建計算對象工廠,根據條件返回不同的對象
public class ArithmeticFactory { public static Arithmetic getArithmetic(String operator){ switch (operator){ case "+": return new Plus(); case "-": return new Substruction(); case "*": return new Multiplication(); case "/": return new Division(); default: throw new RuntimeException("輸入運算符有誤"); } } }
-
驗證
public class MainTest { public static void main(String[] args) { Arithmetic plus = ArithmeticFactory.getArithmetic("+"); double calute = plus.calute(1, 2); System.out.println(calute); Arithmetic division = ArithmeticFactory.getArithmetic("/"); calute = division.calute(1, 0); System.out.println(calute); } }
-
案例結構
爲了方便理解,如下爲本案例結構圖: