1.回调的理解:
public class ShowResult implements ShowImplements {
public static void main(String[] args) {
ShowResult showResult = new ShowResult();
String input = "8 * 9";
CountMethod countMethod = new CountMethod();
// 调用getResult作运算,然后回调在回调方法里显示结果
countMethod.getResult(input, showResult);
}
/**
* 回调此方法
*/
@Override
public void showResult(String input, int result) {
System.out.println("计算:" + input + ";结果为:" + result);
}
}
public class CountMethod {
public void getResult(String input, ShowResult showResult) {
int result = 0;
String[] param = input.split(" ");
int a = Integer.parseInt(param[0]);
String symbol = param[1];
int b = Integer.parseInt(param[2]);
if ("+".equals(symbol)) {
result = a + b;
} else if ("-".equals(symbol)) {
result = a - b;
} else if ("*".equals(symbol)) {
result = a * b;
} else if ("/".equals(symbol)) {
result = a / b;
}
// 回调显示运算结果
showResult.showResult(input, result);
}
}
2.真正的用法是通过接口来使用
public interface ShowImplements {
void showResult(String input, int result);
}
public class ShowResult implements ShowImplements {
public static void main(String[] args) {
ShowResult showResult = new ShowResult();
String input = "8 * 9";
CountMethod countMethod = new CountMethod();
countMethod.getResult(input, showResult);
}
/**
* 回调方法
*/
@Override
public void showResult(String input, int result) {
System.out.println("计算:" + input + ";结果为:" + result);
}
}
public class CountMethod {
public void getResult(String input, ShowImplements someone) {
int result = 0;
String[] param = input.split(" ");
int a = Integer.parseInt(param[0]);
String symbol = param[1];
int b = Integer.parseInt(param[2]);
if ("+".equals(symbol)) {
result = a + b;
} else if ("-".equals(symbol)) {
result = a - b;
} else if ("*".equals(symbol)) {
result = a * b;
} else if ("/".equals(symbol)) {
result = a / b;
}
// 回调显示运算结果
someone.showResult(input, result);
}
}