该模式不属于GOF的23个设计模式,违背了开放封闭原则(对扩展开放,对修改关闭)

    简单的计算器
    类图
    制图工具:draw.io
    SimpleFactoryPattern.drawio.xml
    image.png

    C#代码

    1. public abstract class Arithmetic
    2. {
    3. public double NumberA;
    4. public double NumberB;
    5. public abstract double GetResult();
    6. }
    7. public class SimpleFactory
    8. {
    9. public static Arithmetic CreateOperate(string operate)
    10. {
    11. Arithmetic arithmetic=null;
    12. switch (operate)
    13. {
    14. case "+":
    15. arithmetic = new Add();
    16. break;
    17. case "-":
    18. arithmetic = new Subtract();
    19. break;
    20. case "*":
    21. arithmetic = new Multiply();
    22. break;
    23. case "/":
    24. arithmetic = new Divide();
    25. break;
    26. default:
    27. break;
    28. }
    29. return arithmetic;
    30. }
    31. }
    32. public class Add : Arithmetic
    33. {
    34. public override double GetResult()
    35. {
    36. return NumberA + NumberB;
    37. }
    38. }
    39. public class Subtract : Arithmetic
    40. {
    41. public override double GetResult()
    42. {
    43. return NumberA - NumberB;
    44. }
    45. }
    46. public class Multiply : Arithmetic
    47. {
    48. public override double GetResult()
    49. {
    50. return NumberA * NumberB;
    51. }
    52. }
    53. public class Divide : Arithmetic
    54. {
    55. public override double GetResult()
    56. {
    57. if (NumberB==0)
    58. {
    59. throw new Exception("除数不能为0");
    60. }
    61. return NumberA / NumberB;
    62. }
    63. }

    使用

    1. Arithmetic arithmetic = SimpleFactory.CreateOperate("-");
    2. arithmetic.NumberA = 10;
    3. arithmetic.NumberB = 20;
    4. double result=arithmetic.GetResult();
    5. Console.WriteLine(result);