(1)抽象运算类
package com.liutao.design.model.simpleFactoryModel;
/**
* abstract operation class
* this demo is a caculator to show how to use simple factory mode
*
* @author LIUTAO
* @version 2017/10/25
* @see
*/
public abstract class Operation {
private double numberA;
private double numberB;
public Operation() {
}
public Operation(double numberA, double numberB){
this.numberA = numberA;
this.numberB = 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;
}
/**
* get the result of operation
* @return
*/
public abstract double getResult();
}
(2)加法运算类
package com.liutao.design.model.simpleFactoryModel;
/**
* add operation class
* this demo is a caculator to show how to use simple factory mode
*
* @author LIUTAO
* @version 2017/10/25
* @see
*/
public class AddOperation extends Operation {
@Override
public double getResult() {
return getNumberA()+getNumberB();
}
}
(3)减法运算类
package com.liutao.design.model.simpleFactoryModel;
/**
* sub operation class
* this demo is a caculator to show how to use simple factory mode
*
* @author LIUTAO
* @version 2017/10/25
* @see
*/
public class SubOperation extends Operation {
@Override
public double getResult() {
return getNumberA() - getNumberB();
}
}
(4)运算工厂类
package com.liutao.design.model.simpleFactoryModel;
/**
* operation factory class
* this demo is a caculator to show how to use simple factory mode
*
* the class is used to product the operation object
*
* @author LIUTAO
* @version 2017/10/25
* @see
*/
public class OperationFactory {
public static Operation productOperation(String operationStr){
Operation operation = null;
switch (operationStr){
case "+":operation = new AddOperation();
break;
case "-":operation = new SubOperation();
break;
}
return operation;
}
}
(5)测试类
package com.liutao.design.model.simpleFactoryModel;
/**
* the class is used to test factory mode
*
* @author LIUTAO
* @version 2017/10/25
* @see
*/
public class TestDemo {
public static void main(String[] args) {
//if you want get the result of 2 plus 1
Operation operationPlus = OperationFactory.productOperation("+");
operationPlus.setNumberA(1);
operationPlus.setNumberB(2);
System.out.println("1+2="+operationPlus.getResult());
//if you want get the result of 2 minus 1
Operation operationMinus = OperationFactory.productOperation("-");
operationMinus.setNumberA(2);
operationMinus.setNumberB(1);
System.out.println("2-1="+operationMinus.getResult());
}
}