首页 > 代码库 > 略解简单工厂模式

略解简单工厂模式

  之前在一家公司笔试的时候有过这样一道题:请用一种面向对象语言实现计算器控制台程序,输入两个数字和运算符号,输出结果。

  一开始脑子里想到的是这样滴:

 1 package com.edu.shnu.patternstudy; 2  3 import java.util.Scanner; 4  5 public class Caluate { 6     public static void main(String[] args) { 7         try{ 8             System.out.print("请输入数字m:"); 9             Scanner sc=new Scanner(System.in);10             int m=sc.nextInt();11             System.out.print("请输入运算符号(+、-、*、/):");12             String oper=sc.next();13             System.out.print("请输入数字n:");14             int n=sc.nextInt();15             int result=0;16             switch(oper)17             {18             case "+":19                 result=m+n;20                 break;21             case "-":22                 result=m-n;23                 break;24             case "*":25                 result=m*n;26                 break;27             case "/":28                 if(n!=0)29                     result=m/n;30                 else31                     System.out.println("除数不能为零!");32                 break;33             }34             System.out.println("结果是:"+result);35         }catch(Exception e){36             e.printStackTrace();37         }38     }39 }

  后来想到大话设计模式那本书了(强烈推荐),既然是面向对象语言,那就要封装、继承、多态了:

 1 class OperationAdd extends Operation 2 { 3     Operation oper=new Operation(); 4     @Override 5     public int getResult(){ 6         int result=oper.getM()+oper.getN(); 7         return result; 8     } 9 }10 11 class OperationSub extends Operation12 {13     Operation oper=new Operation();14     @Override15     public int getResult(){16         int result=oper.getM()-oper.getN();17         return result;18     }19 }20 21 class OperationMul extends Operation22 {23     Operation oper=new Operation();24     @Override25     public int getResult(){26         int result=oper.getM()*oper.getN();27         return result;28     }29 }30 31 class OperationDiv extends Operation32 {33     Operation oper=new Operation();34     @Override35     public int getResult(){36         if(oper.getN()==0)37             System.out.println("除数不能为零!");38         int result=oper.getM()/oper.getN();39         return result;40     }41 }

  到底要实例化谁,将来会不会增加新的实例化的对象,这个容易变化,应该考虑用一个单独的类来做创造实例的过程,即工厂。

 1 public class OperationFactory { 2     public static Operation createOperation(String operate){ 3         Operation oper=null; 4         switch(operate){ 5         case "+": 6             oper=new OperationAdd(); 7             break; 8         case "-": 9             oper=new OperationSub();10             break;11         case "*":12             oper=new OperationMul();13             break;14         case "/":15             oper=new OperationDiv();16             break;17         }18         return oper;19     }20 }

main方法中:

1   Operation oper;2    oper=OperationFactory.createOperation("+");3    oper.setM(4);4    oper.setN(2);

 

略解简单工厂模式