首页 > 代码库 > 简单工厂模式
简单工厂模式
站在用户的角度:需要知道运算父类(在相对应的简单工厂模式 对应的是那些子类抽象出来的父类),和简单工厂类,并需要传递操作符获取具体的子类。
站在实现者的角度:需要抽象出父类,并造一个简单工厂
package com.simplefactory1; /** * 抽象的运算类 需要提供公有的数字 * @author 黄二狗 * */ public abstract class Calculator { //第一个数字 private double numberA; //第二个数字 private double numberB; public double getNumberA() { return numberA; } public void setNumberA(double numberA) { this.numberA = numberA; } public double getNumberB() { return numberB; } public void setNumberB(double numberB) { this.numberB = numberB; } public abstract double getResult(); }
package com.simplefactory1; /** * 具体的加法类 减法 等类似 * @author 黄二狗 * */ public class CalculatorAdd extends Calculator{ @Override public double getResult() { double numberA=getNumberA(); double numberB=getNumberB(); return numberA+numberB; } }
package com.simplefactory1; public class CalculatorMinus extends Calculator{ @Override public double getResult() { double numberA=getNumberA(); double numberB=getNumberB(); return numberA-numberB; } }
package com.simplefactory1; public class CalculatorMultiply extends Calculator{ @Override public double getResult() { double numberA=getNumberA(); double numberB=getNumberB(); return numberA*numberB; } }
package com.simplefactory1; public class CalculatorDevide extends Calculator{ @Override public double getResult() { double numberA=getNumberA(); double numberB=getNumberB(); return numberA/numberB; } }
package com.simplefactory1; public class CalculatorFactory { public static Calculator createCalculator(String type) { Calculator cal=null; switch(type) { case "+": cal=new CalculatorAdd(); break; case "-": cal=new CalculatorMinus(); break; case "*": cal=new CalculatorMultiply(); break; case "/": cal=new CalculatorDevide(); break; } return cal; } }
package com.simplefactory1; /** * 用户需要知道工厂 和运算父类 并且需要传递运算操作符 * @author 黄二狗 * */ public class Client { public static void main(String[] args) { System.out.println("测试乘法"); Calculator multiplyCalculator=CalculatorFactory.createCalculator("*"); multiplyCalculator.setNumberA(30); multiplyCalculator.setNumberB(50); System.out.println(multiplyCalculator.getResult()); System.out.println("============================"); System.out.println("测试除法"); Calculator devideCalculator=CalculatorFactory.createCalculator("/"); devideCalculator.setNumberA(30); devideCalculator.setNumberB(50); System.out.println(devideCalculator.getResult()); } }
简单工厂模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。