• 简单工厂模式


    简单工厂模式的本质是利用多态性,将实例化的过程交给工厂去完成,减少耦合度

    实现加减乘除功能的计算器:

    //操作类基类
    public class Operation
    {
    public double NumberA { get; set; }
    public double NumberB { get; set; }
    
    public virtual double GetResult()
    {
    double result = 0;
    return result;
    }
    
    }
    
    //具体的操作类,实现各自的计算逻辑
    public class OperationAdd : Operation
    {
    public override double GetResult()
    {
    return NumberA + NumberB;
    }
    }
    
    public class OperationSub : Operation
    {
    public override double GetResult()
    {
    return NumberA - NumberB;
    }
    }
    
    public class OperationMul : Operation
    {
    public override double GetResult()
    {
    return NumberA * NumberB;
    }
    }
    
    public class OperationDiv : Operation
    {
    public override double GetResult()
    {
    if (NumberB==0)
    {
    throw new Exception("除数不能为0");
    }
    return NumberA / NumberB;
    }
    }
    

    然后构造工厂类,根据客户端传入的参数,实例化不同的操作类,返回给调用者

    public class OperationFactory
        {
            public static Operation CreateOperation(string operation)
            {
                Operation oper = null;
                switch (operation)
                {
                    case "+": oper = new OperationAdd();
                        break;
                    case "-": oper = new OperationSub();
                        break;
                    case "*": oper = new OperationMul();
                        break;
                    case "/": oper = new OperationDiv();
                        break;
                    default:
                        oper = new Operation();
                        break;
                }
                return oper;
            }
        }
    

      客户端调用时,不需要认识所有的操作类,而只需要认识操作类的基类和工厂类即可:

     //乘法
     Operation operMutil = OperationFactory.CreateOperation("*");
     operMutil .NumberA = 3;
     operMutil .NumberB = 5;
     double mutilResult = operMutil .GetResult();
    
     //加法
     Operation operAdd = OperationFactory.CreateOperation("+");
     operAdd .NumberA = 3;
     operAdd .NumberB = 5;
     double addResult = operAdd .GetResult();
    

      

  • 相关阅读:
    通过intent启动Activity
    ubuntu12.04的NFS配置
    内核添加对yaffs2文件系统的支持
    linux内核移植到S5pv210
    nand驱动移植
    tiny210V2 Uboot kernel filesystem 烧写和启动
    linux C++通过ntp协议获取网络时间
    tiny210移植linux内核(3.0.8)杂项
    Ubuntu系统中Sogou输入法面板问题解决方案
    Ubuntu系统中登陆阿里云服务器的方法
  • 原文地址:https://www.cnblogs.com/angela217/p/5345649.html
Copyright © 2020-2023  润新知