一、定义
简单工厂模式关注的问题是如何去实例化对象,到底要实例化谁,将来会不会增加实例化的对象。被创建实例的类型可以是接口、抽象类,也可以是具体的类。
二、UML类图
三、实现
- 操作父类
package com.jthao.design.des.factory;
public class Operation {
private static double numberA;
private static double numberB;
public double getResult() {
double result = 0;
return result;
}
public static double getNumberA() {
return numberA;
}
public void setNumberA(double numberA) {
Operation.numberA = numberA;
}
public double getNumberB() {
return numberB;
}
public void setNumberB(double numberB) {
Operation.numberB = numberB;
}
}
- 具体操作类A
package com.jthao.design.des.factory;
public class OperationAdd extends Operation {
@Override
public double getResult() {
double result = 0;
result = getNumberA() + getNumberB();
return result;
}
}
- 具体操作类B
package com.jthao.design.des.factory;
public class OperationDiv extends Operation {
@Override
public double getResult() {
double result = 0;
result = getNumberA() / getNumberB();
return result;
}
}
- 常量类
package com.jthao.design.des.factory;
public enum OperationEnum {
add("1"), sub("2"), mul("3"), div("4");
String value = "";
private OperationEnum(String value) {
this.value = value;
}
public String getValue() {
return this.value;
}
}
- 工厂类
package com.jthao.design.des.factory;
public class OperationFactory {
public static Operation createOperation(OperationEnum operationEnum) {
Operation operation = null;
switch (operationEnum) {
case add:
operation = new OperationAdd();
break;
case div:
operation = new OperationDiv();
break;
default:
break;
}
return operation;
}
}
- 测试类
package com.jthao.design.des.factory;
public class FactoryTest {
public static void main(String[] args) {
Operation operation = new Operation();
operation.setNumberA(10.0);
operation.setNumberB(20.0);
operation = OperationFactory.createOperation(OperationEnum.add);
System.out.println(operation.getResult());
}
}