Java模板模式
public abstract class Calculator {
abstract int operation(int a, int b);
public int calculate(int a, int b){
return a + b;
}
}
public class Addition extends Calculator {
@Override
int operation(int a, int b){
return a + b;
}
}
public class Subtraction extends Calculator {
@Override
int operation(int a, int b){
return a - b;
}
}
public class Multiplication extends Calculator {
@Override
int operation(int a, int b){
return a * b;
}
}
public class Division extends Calculator {
@Override
int operation(int a, int b){
if(b != 0){
return a / b;
}else{
throw new IllegalArgumentException("Divisor cannot be zero");
}
}
}
public class Main {
public static void main(String[] args) {
Calculator calculator1 = new Addition();
Calculator calculator2 = new Subtraction();
Calculator calculator3 = new Multiplication();
Calculator calculator4 = new Division();
System.out.println("10 + 5 = " + calculator1.calculate(10,5));
System.out.println("10 - 5 = " + calculator2.calculate(10,5));
System.out.println("10 * 5 = " + calculator3.calculate(10,5));
System.out.println("10 / 5 = " + calculator4.calculate(10,5));
}
}