简单工厂模式
目的:通过继承操作类,将单个操作分离出来,前端通过工厂类获取实现对象。
用到:继承、多态、封装
factory-》operation-》getResult()
前端通过调用工厂类获取具体实现对象
import java.util.Scanner; public class main { //实现计算器的功能,输入2个数字和1个运算符号 public static void main(String[] args){ Scanner sc = new Scanner(System.in); double numOne = sc.nextDouble(); sc = new Scanner(System.in); String operate = sc.nextLine(); sc = new Scanner(System.in); double numTwo = sc.nextDouble(); operation operation = operationFactory.createOperation(operate); operation.setNumA(numOne); operation.setNumB(numTwo); double result = operation.getResult(); System.out.println(result); } }
写一个工厂类,获取具体对象,这里也可以通过反射获取具体对象
public class operationFactory { public static operation createOperation(String operate){ operation oper = null; switch (operate){ case "+": oper = new operationAdd(); break; case "-": oper = new operationSub(); break; } return oper; } }
具体实现类
public class operation { private double numA = 0; private double numB = 0; public double getNumA() { return numA; } public void setNumA(double numA) { this.numA = numA; } public double getNumB() { return numB; } public void setNumB(double numB) { this.numB = numB; } public double getResult(){ double result = 0; return result; } }
具体实现,重写getResult()方法
public class operationAdd extends operation { @Override public double getResult(){ return getNumA()+getNumB(); } }
Connected to the target VM, address: '127.0.0.1:39957', transport: 'socket' 5 + 4 9.0 Disconnected from the target VM, address: '127.0.0.1:39957', transport: 'socket' Process finished with exit code 0
相关推荐
Ingram 2019-11-03
liuzhenyu0 2011-07-05
繁殇落幕 2019-06-28
anqier 2019-06-27
scnjl0 2017-04-29
blind 2016-07-29
Vermont 2017-10-16
yunhuaikong 2015-08-09
LazyCat 2014-10-11
pythontty 2019-01-22
蔷薇部落 2011-12-22
liaycn 2011-07-21
liyongkuan 2016-03-16
PHP100 2019-03-28
PHP100 2019-03-27
PHP100 2019-03-27
MATLAB 2018-05-27
vczh的日常 2018-04-12
FashionNote 2018-04-05