工厂方法模式:工厂方法模式定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。
一、简单工厂模式:
实例化对象的时候不再使用 new Object()形式,可以根据用户的选择条件来实例化相关的类。对于客户端来说,去除了具体的类的依赖。只需要给出具体实例的描述给工厂,工厂就会自动返回具体的实例对象。
import lombok.Data;
@Data
public abstract class Operation {
private double numberA = 0;
private double numberB = 0;
public abstract double getResult() throws Exception;
}
public class OperationAdd extends Operation{
@Override
public double getResult() {
return getNumberA() + getNumberB();
}
}
public class OperationSub extends Operation {
@Override
public double getResult() {
return getNumberA() - getNumberB();
}
}
public class OperationMul extends Operation {
@Override
public double getResult() {
return getNumberA() * getNumberB();
}
}
public class OperationDiv extends Operation {
@Override
public double getResult() throws Exception {
if(getNumberB() == 0){
throw new Exception("除数不能为0");
}
return getNumberA() / getNumberB();
}
}
public class OperationFactory {
public static Operation createOperation(String operate){
Operation operation = null;
switch (operate){
case "+" :
operation = new OperationAdd();
break;
case "-" :
operation = new OperationSub();
break;
case "*" :
operation = new OperationMul();
break;
case "/" :
operation = new OperationDiv();
break;
}
return operation;
}
}
public class TestOperation {
public static void main(String[] args) {
Operation operation = OperationFactory.createOperation("+");
try {
operation.setNumberA(10);
operation.setNumberB(20);
System.out.println(operation.getResult());
} catch (Exception e) {
e.printStackTrace();
}
}
}