2018-11-02 20:32:37 开始写
Operation.java类
1 package FactoryMethod;2 3 public abstract class Operation {4 public abstract float getResult(float firstNum, float secondNum);5 }
AddOperation.java类
1 package FactoryMethod; 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 }
共有加减乘除四个来,这就举出一个
IFactory.java类
1 package FactoryMethod;2 3 public interface IFactory {4 public Operation generateOper();5 }
AddOperationFactory.java类
1 package FactoryMethod; 2 3 public class AddOperationFactory implements IFactory { 4 5 @Override 6 public Operation generateOper() { 7 // TODO Auto-generated method stub 8 return new AddOperation(); 9 }10 11 }
共有加减乘除四个来,这就举出一个
Computer.java类
1 package FactoryMethod; 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(count(firstNum, secondNum));15 }16 private static float count(float firstNum, float secondNum) {17 IFactory ifactory = new AddOperationFactory();18 Operation operation = ifactory.generateOper();19 return operation.getResult(firstNum, secondNum);20 }21 22 }
说明:
共需要1个抽象类、n个继承抽象类的具体实现的类(如加减乘除)、1个接口类、n个实现接口类的具体实现的类(返回继承抽象类的具体实现类)、1个主方法调用。
在主方法中有
IFactory ifactory = new AddOperationFactory();向上转型1次(接口类) Operation operation = ifactory.generateOper();向上转型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、Ευχαριστ