using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 简单工厂 { class Program { static void Main(string[] args) { Calculation Fu = Realization.CreateInstance("+"); Fu.Num1 = 1; Fu.Num2 = 2; Console.WriteLine(Fu.CalculationMethod()); } } /// <summary> /// 计算器抽象类 /// </summary> public abstract class Calculation { public int Num1 { get; set; } public int Num2 { get; set; } //抽象计算方法 public abstract int CalculationMethod(); } /// <summary> /// 加法类abstractCalculation /// </summary> public class JiaFa : Calculation { public override int CalculationMethod() { return Num1 +Num2 ; } } /// <summary> /// 减法类abstractCalculation /// </summary> public class JianFa : Calculation { public override int CalculationMethod() { return Num1 - Num2; } } /// <summary> /// 实现类(实现加减乘除) /// </summary> public class Realization { public static Calculation CreateInstance(string operate) { switch (operate) { case "+": return new JiaFa(); case "-": return new JianFa(); default: throw new Exception("无效操作"); } } } }
时间: 2024-10-08 10:08:42