首页 > 其他 > 详细

设计模式--装饰者模式

时间:2019-10-08 23:09:50      阅读:108      评论:0      收藏:0      [点我收藏+]

以一个计算器为例

抽象的计算器接口

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!