首页 > 代码库 > 简单工厂模式
简单工厂模式
Operator.java 类:
package sampleFactory; import java.math.BigDecimal; public abstract class Operator { BigDecimal numA; BigDecimal numB; BigDecimal result ; public abstract BigDecimal getResult(); }
OperatorAdd.java类
package sampleFactory; import java.math.BigDecimal; public class OperatorAdd extends Operator { @Override public BigDecimal getResult() { System.out.println(numA); System.out.println(numB); result = numA.add(numB); return result; } }
OperatorDevide.java类
package sampleFactory; import java.math.BigDecimal; public class OperatorDevide extends Operator { @Override public BigDecimal getResult() { result = numA.divide(numB); return result; } }
OperatorMul.java类
package sampleFactory; import java.math.BigDecimal; public class OperatorMul extends Operator { @Override public BigDecimal getResult() { result = numA.multiply(numB); return result; } }
OperatorSub.java类
package sampleFactory; import java.math.BigDecimal; public class OperatorSub extends Operator { @Override public BigDecimal getResult() { result = numA.subtract(numB); return result; } }
SampleFactory.java类
package sampleFactory; public class SampleFactory { Operator op ; public Operator createOperator(String operator){ switch(operator){ case "+": op = new OperatorAdd(); break; case "-": op = new OperatorSub(); break; case "*": op = new OperatorMul(); break; case "/": op = new OperatorDevide(); } return op ; } }
Business.java类
package sampleFactory; import java.math.BigDecimal; import java.util.Scanner; public class Business { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("请输入数字A:"); BigDecimal numA = sc.nextBigDecimal(); System.out.println("请输入操作符:"); String operator = sc.next(); System.out.println("请输入数字B:"); BigDecimal numB = sc.nextBigDecimal(); SampleFactory sf = new SampleFactory(); Operator op = sf.createOperator(operator); op.numA = numA ; op.numB = numB ; BigDecimal result = op.getResult(); System.out.println("运算结果:"+result); sc.close(); } }
简单工厂模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。