设计模式简单工厂

 

public class Operation
{
    public double One { get; set; } = 0.0;
    public double Two { get; set; } = 0.0;

    public virtual double GetResult()
    {
        return 0.0;
    }
}
public class OperationAdd : Operation 
{
    public override double GetResult()
    {
        return One + Two;
    }
}
public class OperationSub : Operation
{
    public override double GetResult() 
    {
        return One - Two;
    }
}
public class OperationMul : Operation
{
    public override double GetResult()
    {
        return One * Two;
    }
}
public class OperationDiv : Operation
{
    public override double GetResult()
    {
        if (Two == 0) throw new Exception("除数不能为0");
        return One / Two;
    }
}
/// <summary>
/// 简单工厂类
/// </summary>
public class OperationFactory
{
    public static Operation CreateOperate(string operate)
    {
        Operation oper = null;
        switch (operate)
        {
            case "+":
                oper=new OperationAdd();
                break;
            case "-":
                oper = new OperationSub();
                break;
            case "*":
                oper = new OperationMul();
                break;
            case "/":
                oper = new OperationDiv();
                break;
        }
        return oper;
    }
}
 static void Main(string[] args)
 {
     Console.WriteLine("Hello World!");
     //简单工厂 如何实例化对象的问题,到底要实例化谁,将来会不会增加实例化对象,比如增加开根运算,这就很容易变化的地方
     //应该考虑一个单独的类来做这个创造实例的过程,这就是工厂
     var oper=OperationFactory.CreateOperate("*");
     oper.One = 1.9;
     oper.Two = 1.9;
     Console.WriteLine(oper.GetResult());
 }

 

 

posted @ 2024-03-01 08:58  每天学习一点哈哈哈  阅读(6)  评论(0编辑  收藏  举报