工厂方法模式:当需求的变化需要更改简单工厂类的实现时,违背了开放-封闭原则,这时可以通过工厂方法模式,将工厂抽象,为每个具体的实体类创建对应的工厂,实现抽象的工厂接口方法 public class Operation { private double num1; private double num2; public double Num1 { get { return num1; } set { num1 = value; } } public double Num2 { get { return num2; } set { num2 = value; } } public virtual double GetResult() { double ret = 0; return ret; } } public class OperationAdd:Operation { public override double GetResult() { return Num1 + Num2; } } public class OperationSub:Operation { public override double GetResult() { return Num1 - Num2; } } public class OperationMul:Operation { public override double GetResult() { return Num1 * Num2; } } public class OperationDiv:Operation { public override double GetResult() { double value = 0; if (Num2 == 0) { throw new Exception("除数不能为零"); } value = Num1 / Num2; return value; } } #region 工厂方法模式 interface IOperationFactory { Operation CreateOperationInstence(); } class OperationAddFactory : IOperationFactory { public Operation CreateOperationInstence() { return new OperationAdd(); } } class OperationSubFactory : IOperationFactory { public Operation CreateOperationInstence() { return new OperationSub(); } } class OperationMulFactory : IOperationFactory { public Operation CreateOperationInstence() { return new OperationMul(); } } class OperationDivFactory : IOperationFactory { public Operation CreateOperationInstence() { return new OperationDiv(); } } #endregion class Program { static void Main(string[] args) { #region 工厂方法模式 IOperationFactory iOperationFactory = new OperationAddFactory(); Operation myOperation = iOperationFactory.CreateOperationInstence(); myOperation.Num1 = 5; myOperation.Num2 = 6; Console.WriteLine("工厂方法模式运行效果:"); Console.WriteLine("结果为 5+6= " + myOperation.GetResult()); #endregion } }