1 package com.main.cul; 2 import java.util.Scanner; 3 import com.factory.Operation; 4 public class Demo { 5 private static double result; 6 public static void main(String[] argv){ 7 8 try{ 9 10 Scanner in=new Scanner(System.in); 11 System.out.print("请输入数字A:"); 12 double numA=in.nextDouble(); 13 14 System.out.print("请选择操作+-*/(加减乘除):"); 15 String strOper=in.next(); 16 char operate=strOper.charAt(0); 17 18 System.out.print("请输入数字B:"); 19 double numB=in.nextDouble(); 20 System.out.println("您输入的数字A:"+numA); 21 System.out.println("您输入的操作:"+operate); 22 System.out.println("您输入的数字B:"+numB); 23 Operation oper=OperationFactory.createOperate(operate); 24 Demo.result=oper.getResult(numA,numB); 25 System.out.print("结果为"+result); 26 27 }catch (Exception e) { 28 // TODO: handle exception 29 e.printStackTrace(); 30 } 31 } 32 }
工厂类
1 package com.main.cul; 2 3 import com.factory.AddOper; 4 import com.factory.DivOper; 5 import com.factory.MulOper; 6 import com.factory.Operation; 7 import com.factory.SubOper; 8 9 10 11 public abstract class OperationFactory { 12 13 public static Operation createOperate(char ope){ 14 Operation oper =null; 15 switch (ope) { 16 case '+': 17 oper =new AddOper(); 18 break; 19 case '-': 20 oper =new SubOper(); 21 break; 22 case '*': 23 oper =new MulOper(); 24 break; 25 case '/': 26 oper =new DivOper(); 27 break; 28 } 29 return oper;} 30 }
加减乘除类:
1 package com.factory; 2 3 public abstract class Operation { 4 protected double numA; 5 protected double numB; 6 protected double result; 7 public abstract double getResult(double numA, double numB); 8 }
1 package com.factory; 2 3 public class AddOper extends Operation { 4 5 public double getResult(double numA,double numB){ 6 result=numA+numB; 7 return result; 8 9 } 10 }
package com.factory; public class SubOper extends Operation { public double getResult(double numA,double numB){ result=numA-numB; return result; } }
1 package com.factory; 2 public class MulOper extends Operation { 3 public double getResult(double numA,double numB){ 4 result=numA*numB; 5 return result; 6 7 } 8 }
1 package com.factory; 2 public class DivOper extends Operation { 3 public double getResult(double numA,double numB){ 4 if(numB==0){ 5 6 System.out.print("除数不能为0"); 7 } 8 result=numA/numB; 9 return result; 10 11 } 12 }