试着用java实现了一下 废话少说上代码
operator.class
package org.ustc.simplefactory;
public class Operator {
int num1;
int num2;
public int getNum1() {
return num1;
}
public void setNum1(int num1) {
this.num1 = num1;
}
public int getNum2() {
return num2;
}
public void setNum2(int num2) {
this.num2 = num2;
}
public double getResult(){
return 0;
}
}
几个继承类
package org.ustc.simplefactory;
//实现加法
public class AddOperator extends Operator {
@Override
public double getResult() {
// TODO Auto-generated method stub
return num1+num2;
}
}
package org.ustc.simplefactory;
public class DevideOperator extends Operator {
@Override
public double getResult() {
// TODO Auto-generated method stub
double d = 0.0;
try{
d = num1/num2;
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return d;
}
}
package org.ustc.simplefactory;
public class MinusOperator extends Operator {
@Override
public double getResult() {
// TODO Auto-generated method stub
return num1-num2;
}
}
package org.ustc.simplefactory;
public class MutipleOperator extends Operator {
@Override
public double getResult() {
// TODO Auto-generated method stub
return num1*num2;
}
}
工厂方法类
package org.ustc.simplefactory;
public class SimpleFacetory {
public static Operator choseOperator(char c){
Operator operator = null;
switch(c){
case '+':
operator = new AddOperator();
break;
case '-':
operator = new MinusOperator();
break;
case '*':
operator = new MutipleOperator();
break;
case '/':
operator = new DevideOperator();
break;
}
return operator;
}
}
package org.ustc.simplefactory;
public class Main {
public static void main(String[] args) {
Operator operator = SimpleFacetory.choseOperator('/');
operator.setNum1(1);
operator.setNum2(0);
System.out.println("结果是:"+operator.getResult());
}
}