Java学习笔记——设计模式之一.简单工厂

蜀道之难。难于上青天,侧身西望长咨嗟

                 ——蜀道难

类图:

 

定义Operation类

 1 package cn.no1.simplefactory;
 2 
 3 public abstract class Operation {
 4 
 5     private double numA;
 6     private double numB;
 7 
 8     public double getNumA() {
 9         return numA;
10     }
11 
12 
13     public void setNumA(double numA) {
14         this.numA = numA;
15     }
16 
17 
18     public double getNumB() {
19         return numB;
20     }
21 
22 
23     public void setNumB(double numB) {
24         this.numB = numB;
25     }
26 
27     public abstract double calculate ();
28 }

定义其四个子类

 1 package cn.no1.simplefactory;
 2 
 3 public class OperationAdd extends Operation{
 4 
 5     @Override
 6     public double calculate() {
 7         // TODO Auto-generated method stub
 8         return this.getNumA() + this.getNumB();
 9     }
10 
11 }
12 public class OperationSub extends Operation {
13 
14     @Override
15     public double calculate() {
16         // TODO Auto-generated method stub
17         return this.getNumA()-this.getNumB();
18     }
19 
20 }
21 public class OperationMultiply extends Operation{
22 
23     @Override
24     public double calculate() {
25         // TODO Auto-generated method stub
26         return this.getNumA()*this.getNumB();
27     }
28     
29 }
30 public class OperationDivide extends Operation{
31 
32     @Override
33     public double calculate() {
34         // TODO Auto-generated method stub
35         return this.getNumA()/this.getNumB();
36     }
37 
38 }

定义工厂类

 1 package cn.no1.simplefactory;
 2 
 3 public class OperationFactory {
 4 
 5     public static Operation createOperation(String operator){
 6         Operation operation = null;
 7         switch (operator) {
 8         case "+":
 9             operation = new OperationAdd();
10             break;
11         case "-":
12             operation = new OperationSub();
13             break;
14         case "*":
15             operation = new OperationMultiply();
16             break;
17         case "/":
18             operation = new OperationDivide();
19             break;
20      }
21         return operation;
22     }
23 }

测试类:

 1 package cn.no1.simplefactory;
 2 
 3 import java.util.Scanner;
 4 
 5 public class _Test {
 6 
 7     public static void main(String[] args) {
 8         Scanner sc = new Scanner(System.in);
 9         System.out.println("输入数字1:");
10         double numA = sc.nextDouble();
11         System.out.println("输入数字2:");
12         double numB = sc.nextDouble();
13         System.out.println("输入操作符:");
14         String operator = sc.next();
15         sc.close();
16         Operation operation = OperationFactory.createOperation(operator);
17         operation.setNumA(numA);
18         operation.setNumB(numB);
19         double result = operation.calculate();
20         System.out.println("计算结果是:"+result);
21     }
22 }

 

posted @ 2017-05-13 00:49  Tomas曼  Views(174)  Comments(0Edit  收藏  举报