-
需求:写个计算器,能完成加减乘除运算
- 定义接口做参数
- 加减乘除定义4个类
- 定义一个静态工具类,把下面的接口作为其中一个形参对象,传递具体的运算符类完成计算
-
定义一个接口
public interface IComputer {
int compute(int num1, int num2);
}
- 定义加减乘除4个类
public class AddOper implements IComputer {
@Override
public int compute(int num1, int num2) {
return num1 + num2;
}
}
public class SubOper implements IComputer {
@Override
public int compute(int num1, int num2) {
return num1 - num2;
}
}
public class MulOper implements IComputer {
@Override
public int compute(int num1, int num2) {
return num1 * num2;
}
}
public class DivideOper implements IComputer {
@Override
public int compute(int num1, int num2) {
try {
return num1 / num2;
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
}
- 定义一个静态工具类
public class UserComputer {
public static void compute(IComputer computer, int num1, int num2) {
System.out.println(computer.compute(num1, num2));
}
public static void main(String[] args) {
UserComputer.compute(new AddOper(), 1, 2);
UserComputer.compute(new SubOper(), 1, 2);
UserComputer.compute(new MulOper(), 1, 2);
UserComputer.compute(new DivideOper(), 1, 2);
}
}