zoukankan      html  css  js  c++  java
  • (01)大话设计模式-简单工厂-java实现

    1.运算接口

    public interface Operation {
    	public double getResult(double NumberA , double NumberB);
    }
    

    2.加减乘除类

    public class OperationAdd implements Operation {
    
    	@Override
    	public double getResult(double NumberA, double NumberB) {
    		return NumberA + NumberB;  
    		
    	}
    
    }
    public class OperationSub implements Operation {
    
    @Override
    public double getResult(double NumberA, double NumberB) {
    return NumberA - NumberB; 
    }
    
    }
    public class OperationMul implements Operation {
    
    	@Override
    	public double getResult(double NumberA, double NumberB) {
    		return NumberA * NumberB;  
    	}
    
    }
    public class OperationDiv implements Operation {
    
    	@Override
    	public double getResult(double NumberA, double NumberB) {
    		if(NumberB==0)
    		try {
    			throw new Exception("除数不能为0");
    		} catch (Exception e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		return NumberA / NumberB;  
    	}
    
    }
    

    3.简单运算工厂类

    public class OperationFactory {
    	public static Operation createOperate(String operate){
    		Operation oper = null;
    		switch(operate)
    		{
    		case "+":
    		oper = new OperationAdd();
    		break;
    		case "-":
    		oper = new OperationSub();
    		break;
    		case "*":
    		oper = new OperationMul();
    		break;
    		case "/":
    		oper = new OperationDiv();
    		break;
    		}
    		return oper;
    	}
    
    }
    

    4.测试类

    public class test {
    	public static void main(String[] args){
    		Operation oper;
    		oper = OperationFactory.createOperate("+");	
    		System.out.println(oper.getResult(1, 2));
    	}
    }
    

      

     

    -------------------------------------------------------------------------
    ## 极客时间全网最便宜最优惠购买方式,优惠券返现 百度网盘 微信关注公众号“选门好课”
    扫描下方二维码关注我的公众号"选门好课",与我一起交流知识
  • 相关阅读:
    N天学习一个linux命令之scp
    php svn仓库提交预处理
    NTP-网络时间协议
    N天学习一个linux命令之umask
    N天学习一个linux命令之xz
    N天学习一个linux命令之xargs
    N天学习一个Linux命令之hostnamectl
    jQuery easyUI的datagrid,如何在翻页以后仍能记录被选中的行
    multiselect2side:jQuery多选列表框插件
    springmvc+jquery实现省市区地址下拉框联动
  • 原文地址:https://www.cnblogs.com/singworld/p/8956019.html
Copyright © 2011-2022 走看看