1 这里是一个计算器,运算规则为 加减乘除,输出相应的结果
2 UML图
3 java类
Counter.java (抽象接口)
package DesignPattern.calculator; public interface Counter { public double getResult(); }
package DesignPattern.calculator; public class AddCounter implements Counter { private double x; private double y; public AddCounter(double x,double y){ this.x = x; this.y = y; } @Override public double getResult() { return this.x + this.y; } }
package DesignPattern.calculator; public class DivCounter implements Counter { private double x; private double y; public DivCounter(double x,double y){ this.x = x; this.y = y; } @Override public double getResult() { return this.x - this.y; } }
MulCounter.java (乘法类)
package DesignPattern.calculator; public class MulCounter implements Counter { private double x; private double y; public MulCounter(double x,double y){ this.x = x; this.y = y; } @Override public double getResult() { return this.x * this.y; } }
package DesignPattern.calculator; public class SubCounter implements Counter { private double x; private double y; public SubCounter(double x,double y){ this.x = x; this.y = y; } @Override public double getResult() { double result = 0; if(this.y == 0){ try { throw new MyException("被除数为0"); } catch (MyException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else{ result = this.x/this.y; } return result; } }
package DesignPattern.calculator; public class ErrorCounter implements Counter { private double x; private double y; public ErrorCounter(double x,double y){ this.x = x; this.y = y; } @Override public double getResult() { try { throw new MyException("异常:错误的计算类"); } catch (MyException e) { // TODO Auto-generated catch block e.printStackTrace(); } return 0; } }
package DesignPattern.calculator; public class MyException extends Exception { public MyException(String str){ System.out.println(str); } }
Client.java (客户端)
package DesignPattern.calculator; public class Client { public static void main(String[] args) { double x = 10,y =20; Counter Counter; // 加法 Counter = Factory.createCounter('+', x, y); System.out.println("加法结果为 : " + Counter.getResult()); //减法 Counter = Factory.createCounter('-', x, y); System.out.println("减法的结果为 : " + Counter.getResult()); //乘法 Counter = Factory.createCounter('*', x, y); System.out.println("乘法的结果为 : " + Counter.getResult()); //除法 Counter = Factory.createCounter('/', x, y); System.out.println("除法的结果为 : " + Counter.getResult()); //除法 ,被除数为0 Counter = Factory.createCounter('/', x, 0); System.out.println("除法的结果为 : " + Counter.getResult()); //未知 Counter = Factory.createCounter('?', x, y); System.out.println("未知规则的结果 : " + Counter.getResult()); } }