简单工厂
程序员文章站
2022-05-28 20:07:28
2018-11-02 20:27:28开始写 Operation.java类 AddOperation.java类 共有加减乘除四个来,这就举出一个 OperationFactory.java类 Computer.java类 这是主类 说明:简单工厂也是静态工厂方法模式(Static Factory ......
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、ευχαριστ