你能告诉我这条线是怎么工作的吗..。我的OperatorFactory.get("add")没有做任何事情。我不会把任何东西印出来
ArithmeticOperator add = OperatorFactory.get ("add");当我有以下情况时:
interface ArithmeticOperator {
// Returns the result of applying the operator to operands a and b.
double operate (double a, double b);
// Return a String that is the name of this operator.
String printName ();
}
public class OperatorFactory implements ArithmeticOperator {
public OperatorFactory(){
}
public static ArithmeticOperator get(String name){
if(name.equals("add"))
return new PlusOperator();
else if(name.equals("sub"))
return new SubOperator();
else if(name.equals("mult"))
return new MultOperator();
else if(name.equals("div"))
return new DivOperator();
else
return null;
}
public double operate(double a, double b) {
throw new UnsupportedOperationException("Not supported yet.");
}
public String printName() {
throw new UnsupportedOperationException("Not supported yet.");
}
}public class PlusOperator extends OperatorFactory {
public double operate(double a, double b) {
return a + b;
}
public String printName() {
return "Add";
}
}
public class PlusOperator extends OperatorFactory {
public double operate(double a, double b) {
return a + b;
}
public String printName() {
return "Add";
}
}发布于 2010-03-11 14:58:51
您从不调用add.printName(),当然也不会输出任何内容,所以我并不奇怪什么都没有打印出来。
发布于 2010-03-11 15:00:29
你真的试过打印名字吗?
ArithmeticOperator add = OperatorFactory.get ("add");
System.out.println(add.printName());另外,PlusOperator应该直接实现ArithmeticOperator。工厂不应该实现ArithmeticOperator。这允许您从工厂类中移除操作和printName方法。
发布于 2010-03-11 15:00:19
不像get()方法调用printName(),因此不应该打印任何内容。
https://stackoverflow.com/questions/2425927
复制相似问题