简单工厂模式

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

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();

 

posted @ 2016-05-02 11:05  Leo的日记本  阅读(179)  评论(0编辑  收藏  举报