讀書筆記《程式碼整潔之道》迭進
阿新 • • 發佈:2022-03-08
簡單工廠模式
用一個開發計算器的例子來講解簡單工廠模式,剛開始開發這個計算器的時候程式碼是這樣的;
package out; import java.util.Scanner; import java.util.*; public class SimpleFactoryPattern{ public static void main(String[]args){ try{ System.out.println("輸入數字A:"); Scanner sca = new Scanner(System.in); Integer inA = sca.nextInt(); String strNumberA = Integer.toString(inA); // System.out.println(strNumberA); System.out.println("輸入運算子:"); // Scanner optscan = new Scanner(System.in); String optstr = sca.next(); // Println(optstr); System.out.println("輸入數字B:"); // Scanner sc Integer intB = sca.nextInt(); String strNumberB = Integer.toString(intB); String result = ""; Integer re = null; switch(optstr){ case "+": re = (Integer.parseInt(strNumberA)+Integer.parseInt(strNumberB)); result = new String(re.toString()); System.out.println("輸出結果:"+result); break; case "-": re = Integer.parseInt(strNumberA)-Integer.parseInt(strNumberB); result = new String(re.toString()); System.out.println("輸出結果:"+result); break; case "*": re = Integer.parseInt(strNumberA)*Integer.parseInt(strNumberB); result = new String(re.toString()); System.out.println("輸出結果:"+result); break; case "/": if(strNumberB != "0"){ re = Integer.parseInt(strNumberA)/Integer.parseInt(strNumberB); result = new String(re.toString()); }else{ result = "除數不能為0"; } System.out.println("輸出結果:"+result); break; } }catch(Exception e){ } }