2018-11-02 20:27:28开始写
Operation.java类
1 package StaticFactoryMethedPattern; 2 3 public abstract class Operation { 4 public abstract float getResult(float firstNum, float secondNum); 5 }
AddOperation.java类
1 package StaticFactoryMethedPattern; 2 3 public class AddOperation extends Operation { 4 5 @Override 6 public float getResult(float firstNum, float secondNum) { 7 // TODO Auto-generated method stub 8 return firstNum + secondNum; 9 } 10 11 }
共有加减乘除四个来,这就举出一个
OperationFactory.java类
1 package StaticFactoryMethedPattern; 2 3 public class OperationFactory { 4 public static Operation getOperation(String quotaFlag) { 5 Operation o = null; 6 switch (quotaFlag) { 7 case "+" : 8 o = new AddOperation(); 9 break; 10 case "-" : 11 o = new SubOperation(); 12 break; 13 case "*" : 14 o = new MulOperation(); 15 break; 16 case "/" : 17 o = new DivOperation(); 18 break; 19 default : 20 break; 21 } 22 return o; 23 } 24 }
Computer.java类 这是主类
1 package StaticFactoryMethedPattern; 2 3 import java.util.Scanner; 4 5 public class Computer { 6 7 public static void main(String[] args) { 8 // TODO Auto-generated method stub 9 Scanner scan = new Scanner(System.in); 10 System.out.println("请输入第一个数字:"); 11 float firstNum = scan.nextFloat(); 12 System.out.println("请输入第二个数字:"); 13 float secondNum = scan.nextFloat(); 14 System.out.println("请输入运算符号:"); 15 String countQuota = scan.next(); 16 System.out.println(count(firstNum, secondNum, countQuota)); 17 } 18 private static float count(float firstNum, float secondNum, String countQuota) { 19 Operation operation = OperationFactory.getOperation(countQuota); 20 return operation.getResult(firstNum, secondNum); 21 } 22 23 }
说明:简单工厂也是静态工厂方法模式(Static FactoryMethod Pattern)
共需要1个抽象类、n个继承抽象类的具体实现的类(如加减乘除)、1个加工类(通过switch-case语句)、1个主方法调用。
在主方法中有
Operation operation = OperationFactory.getOperation(countQuota);向上转型1次(抽象类)
return operation.getResult(firstNum, secondNum);最后调用子类方法返回结果
谢谢、Thank you、Salamat Do(撒拉玛特朵)、あリがCám o*n(嘉蒙)とゥ(阿里嘎都)、감사합니다 (勘三哈咪瘩)、terima Kasih(得力马卡系)、kob-khun(寇布库恩)、dhanyavaad(达尼阿瓦德)、toda(透达)、te?ekkür ederim(特谢库尔埃戴里姆)、Dzie,kuje(以库以而)、Spasibo(思巴喜柏)、Danke(但可)、shokran(休克朗)、Obrigada(欧布哩嘎搭)、dank u(当Q)、Merci(梅呵西)、Gracias(格拉喜亚思)、Grazie(格啦姬)、Благодарности、Tak、Kiitos、Díky、Hvala、Mul?umesc、Takk、Ευχαριστ