以一个计算器为例
抽象的计算器接口
public interface Calculator { double calculate(double a, double b, String op); }
计算方法抽象类,用于装饰计算器
public abstract class Operate implements Calculator { Calculator calculator; public Operate(Calculator calculator) { this.calculator = calculator; } }
普通的加减乘除计算机,实现Calculator接口
public class SimpleCalculator implements Calculator { @Override public double calculate(double a, double b, String op) { if ("+".equals(op)) { return a + b; } else if ("-".equals(op)) { return a - b; } else if ("*".equals(op)) { return a * b; } else if ("/".equals(op)) { if (b == 0) { throw new IllegalArgumentException("除数不能为0"); } return a / b; } else { throw new IllegalArgumentException(op + "不合法"); } } }
mod计算方法,继承Operate抽象类
public class ModOperate extends Operate { public ModOperate(Calculator calculator) { super(calculator); } @Override public double calculate(double a, double b, String op) { try { return calculator.calculate(a, b, op); } catch (IllegalArgumentException e) { if (op.equals("%")) { return a % b; } throw e; } } }
pow计算方法,同样继承Operate抽象类
public class PowOperate extends Operate { public PowOperate(Calculator calculator) { super(calculator); } @Override public double calculate(double a, double b, String op) { try { return calculator.calculate(a, b, op); } catch (IllegalArgumentException e) { if (op.equals("pow")) { return Math.pow(a, b); } throw e; } } }
测试类
public class Main { public static void main(String args[]) { Calculator calculator = new SimpleCalculator(); // 给simpleCalculator修饰一下,实现了更多的计算方法 Operate operate = new PowOperate(calculator); operate = new ModOperate(operate); System.out.println(operate.calculate(1, 2, "+")); System.out.println(operate.calculate(1, 2, "-")); System.out.println(operate.calculate(1, 2, "*")); System.out.println(operate.calculate(1, 2, "/")); // 除数为0 // System.out.println(operate.calculate(1, 0, "/")); System.out.println(operate.calculate(1, 2, "%")); System.out.println(operate.calculate(1, 2, "pow")); System.out.println(operate.calculate(1, 2, "&&&&&")); } }
测试结果
3.0 -1.0 2.0 0.5 1.0 1.0 Exception in thread "main" java.lang.IllegalArgumentException: &&&&&不合法 at decorator.SimpleCalculator.calculate(SimpleCalculator.java:19) at decorator.PowOperate.calculate(PowOperate.java:12) at decorator.ModOperate.calculate(ModOperate.java:12) at decorator.Main.main(Main.java:17)
原文:https://www.cnblogs.com/lz-0011/p/11638205.html