类图:
代码:
1 public class Operation { 2 3 protected double numberA = 0; 4 protected double numberB = 0; 5 6 7 public double getNumberA() { 8 return numberA; 9 } 10 public void setNumberA(double numberA) { 11 this.numberA = numberA; 12 } 13 public double getNumberB() { 14 return numberB; 15 } 16 public void setNumberB(double numberB) { 17 this.numberB = numberB; 18 } 19 20 protected double getResult() 21 { 22 double result = 0; 23 return result; 24 } 25 26 27 }
1 public class AddOperation extends Operation{ 2 3 @Override 4 public double getResult() 5 { 6 return numberA + numberB; 7 8 } 9 10 11 }
1 public class OperationFactory { 2 3 public static Operation createOperation(String operate) 4 { 5 if (operate.equals("+")) 6 { 7 return new AddOperation(); 8 } 9 else if (operate.equals("*")) 10 { 11 return new MutiOperation(); 12 } 13 return null; 14 } 15 }
1 public class Client { 2 3 public static void main(String[] args) 4 { 5 Operation add = OperationFactory.createOperation("+"); 6 add.setNumberA(1); 7 add.setNumberB(2); 8 System.out.println(add.getResult()); 9 } 10 }