zoukankan      html  css  js  c++  java
  • 简单工厂模式

    通过一个计算器的例子来学习简单工厂

    1、Operation 运算类

    public class Operation
    {
        private double _numberA=0;
        private double _numberB=0;
    
        public double NumberA
        {
            get{return _numberA}
            set{_numberA=value;}
        }
    
         public double NumberB
        {
            get{return _numberB}
            set{_numberB=value;}
        }
    
        public virtual double GetResult()  //虚方法,方便子类重写
        {
            double result=0;
            return result;
        }
    }

    2、加减乘除类

    class OpertionAdd:Operation  //加法类
    {
        public override double GetResult()
        {
            double result=0;
            result =NumberA+NumberB;
            return result;
        }
    }
    
    class OpertionSub:Operation  //减法类
    {
        public override double GetResult()
        {
            double result=0;
            result =NumberA-NumberB;
            return result;
        }
    }
    
    class OpertionMul:Operation  //乘法类
    {
        public override double GetResult()
        {
            double result=0;
            result =NumberA*NumberB;
            return result;
        }
    }
    
    
    class OpertionDiv:Operation  //除法类
    {
        public override double GetResult()
        {
            double result=0;
            if(NumberB==0)
            {
                throw new Exception("除数不能为0");
            }
            result =NumberA/NumberB;
            return result;
        }
    }

    3、简单运算工厂类

    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;
            }
        }
    }

    4、客户端代码

    Operation oper;
    oper=OperationFactory.CreateOperate("+");
    oper.NumberA=1;
    oper.NumberB=2;
    double result=oper.GetResult();
  • 相关阅读:
    linux 常用命令(个人记录)
    jmeter 5.0版本更新说明(个人做个记录)
    Netdata---Linux系统性能实时监控平台部署记录
    MySQL Yum存储库 安装、升级、集群
    linux 各项配置汇总
    构建Maven项目自动下载jar包
    计算服务器的pv量算法
    性能计算公式
    jstack(查看线程)、jmap(查看内存)和jstat(性能分析)命令
    结构模式
  • 原文地址:https://www.cnblogs.com/shanoon/p/5452033.html
Copyright © 2011-2022 走看看