介紹 簡單工廠模式
介紹 簡單工廠模式
介紹 簡單工廠模式
根據https://davidchenblog.com/posts/adfcf909/#more
可以運用簡單工廠模式重構
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| public class OperationFactory { public static Operation createOperate(String operate) { Operation oper = null; switch (operate) { case "+": oper = new Add(); break; case "-": oper = new Sub(); break; case "*": oper = new Mul(); break; case "/": oper = new Div(); break; defautl: break; } return oper; } }
輸入運算符號,工廠會實體化出合適的物件, 透過多型,傳回父類別的方式實現了計算機結果。
|
1 2 3 4 5 6
| 使用工廠類別方法example
Operation oper = OperationFactory.createOperate("+"); oper.NumberA = 1; oper.NumberB = 2; double result = oper.GetResult();
|