• 简单工厂模式练习


     输入两个数和运算符,计算出结果。

    可以根据工厂模式画出类图,四种(或者更多)运算符,统一运算符接口,并含有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
  • 相关阅读:
    [FAQ] jsoneditor 如何切换 mode 或者选择 modes
    IDA动态调试快捷键
    [FAQ] PHP Warning: json_encode(): double INF does not conform to the JSON spec
    Git 工具下载慢问题 & 图像化界面工具
    Windows 查看端口是被什么程序占用
    什么是 objdump 命令
    什么是 IDA 工具
    什么是 ELF 文件(文件格式)
    ARM 反汇编速成
    [Mobi] Android Studio NDK 安装
  • 原文地址:https://www.cnblogs.com/yuhanghzsd/p/5377957.html
Copyright © 2020-2023  润新知