工厂方法模式(Factory Method Pattern)是一种创建型设计模式,它定义了一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法模式使得一个类的实例化延迟到其子类。
// 举例
public abstract class Operation
{
public abstract double Calculate(double a, double b);
}
public class AddOperation : Operation
{
public override double Calculate(double a, double b)
{
return a + b;
}
}
public class SubtractOperation : Operation
{
public override double Calculate(double a, double b)
{
return a - b;
}
}
public class MultiplyOperation : Operation
{
public override double Calculate(double a, double b)
{
return a * b;
}
}
public class DivideOperation : Operation
{
public override double Calculate(double a, double b)
{
if (b == 0)
{
throw new DivideByZeroException();
}
return a / b;
}
}
// 工厂类
public abstract class OperationFactory
{
public abstract Operation CreateOperation();
}
public class AddOperationFactory : OperationFactory
{
public override Operation CreateOperation()
{
return new AddOperation();
}
}
public class SubtractOperationFactory : OperationFactory
{
public override Operation CreateOperation()
{
return new SubtractOperation();
}
}
public class MultiplyOperationFactory : OperationFactory
{
public override Operation CreateOperation()
{
return new MultiplyOperation();
}
}
public class DivideOperationFactory : OperationFactory
{
public override Operation CreateOperation()
{
return new DivideOperation();
}
}
// 使用示例
OperationFactory factory = new AddOperationFactory();
Operation operation = factory.CreateOperation();
double result = operation.Calculate(1, 2);
Console.WriteLine("1 + 2 = " + result);
factory = new SubtractOperationFactory();
operation = factory.CreateOperation();
result = operation.Calculate(3, 4);
Console.WriteLine("3 - 4 = " + result);
factory = new MultiplyOperationFactory();
operation = factory.CreateOperation();
result = operation.Calculate(5, 6);
Console.WriteLine("5 * 6 = " + result);
factory = new DivideOperationFactory();
operation = factory.CreateOperation();
result = operation.Calculate(7, 8);
Console.WriteLine("7 / 8 = " + result);