ITPub博客

首页 > Linux操作系统 > Linux操作系统 > 简单工厂模式---四则运算

简单工厂模式---四则运算

原创 Linux操作系统 作者:tyoodz 时间:2012-03-23 14:50:49 0 删除 编辑

根据不同的运算符实例化不同的对象


class Operation
{
  protected double numA = 0;
  protected double numB = 0;

  public double GetResult()
  {
    double result = 0;
    return result;
  }
 
  protected void set_A(int a){
  numA = a;
  }

  protected void set_B(int b){numB = b;}
}

class OperationAdd extends Operation
{
  public double GetResult()
  {
    double result = 0;
    result = numA + numB;
    return result;
  }
}

class OperationSub extends Operation
{
  public double GetResult()
  {
    double result = 0;
    result = numA - numB;
    return result;
  }
}

class OperationMul extends Operation
{
  public double GetResult()
  {
    double result = 0;
    result = numA * numB;
    return result;
  }
}

class OperationDiv extends Operation
{
  public double GetResult()
  {
    double result = 0;
    if (numB != 0)
    result = numA / numB;
    return result;
  }
}

class OperationFactory
{
  public static Operation createOperate(String operate)
  {
    Operation per = null;
    if (operate == "+"){
        per = new OperationAdd();
    }
    else if (operate == "-")
        per = new OperationSub();
    else if (operate == "*")
        per = new OperationMul();
    return oper;
  }
}


public class test {
 public static void main(String[] args) {
  Operation oper;
                per = OperationFactory.createOperate("+");
                oper.set_A(9);
                oper.set_B(9);
                System.out.println(oper.GetResult());
                per = OperationFactory.createOperate("-");
                System.out.println(oper.GetResult());
 }
}

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/25361369/viewspace-719360/,如需转载,请注明出处,否则将追究法律责任。

下一篇: 策略模式
请登录后发表评论 登录
全部评论

注册时间:2011-05-16

  • 博文量
    55
  • 访问量
    74251