输入两个数和运算符,计算出结果。
可以根据工厂模式画出类图,四种(或者更多)运算符,统一运算符接口,并含有run()方法,用于执行运算。
定义一个运算工厂,含有工厂方法,该工厂方法根据用户输入的运算符new出相应的对象。
Main测试
import java.util.Scanner; public class Main { public static void main(String args[]){ System.out.println("输入两个数和运算符号"); Scanner in=new Scanner(System.in); double n1 = in.nextDouble(); double n2 = in.nextDouble(); String s3 = in.next(); in.close(); OperatorStore operatorStore = new SimpleOperator(n1,n2,s3); operatorStore.runOperator(n1,n2,s3); } }
运算接口
public abstract class Operator { protected void run (double n1, double n2){ System.out.println("Operator run"); } }
加减乘除
public class Plus extends Operator { double n1,n2,n3; public Plus(double n1 ,double n2){ this.n1=n1; this.n2=n2; } protected void run(double n1,double n2){ n3=n1+n2; System.out.println("和为"+n3); } }
工厂
public abstract class OperatorStore { Operator operator; public Operator runOperator(double n1 ,double n2,String type){ operator = createoperator(type); operator.run(n1, n2); return operator; } public abstract Operator createoperator(String type); }
工厂方法
public class SimpleOperator extends OperatorStore{ double n1,n2; String type; public SimpleOperator(double n1,double n2,String s3){ this.n1 = n1; this.n2=n2; this.type=s3; } public Operator createoperator(String type) { System.out.println(type); if(type.equals("+")){ return new Plus(n1,n2); } if(type.equals("-")){ return new subtraction(n1,n2); }else return null; } }
执行结果
输入两个数和运算符号 3.4 4.5 - - 差为-1.1