简单工厂模式实现方式
@Setter
@Getter
public abstract class Operation {
private double value1 = 0;
private double value2 = 0;
protected abstract double getResule();
}
public class OperationAdd extends Operation {
@Override
protected double getResule() {
return getValue1() + getValue2();
}
}
public class OperationSub extends Operation {
@Override
protected double getResule() {
return getValue1() - getValue2();
}
}
public class OperationMul extends Operation {
@Override
protected double getResule() {
return getValue1() * getValue2();
}
}
public class OperationDiv extends Operation {
@Override
protected double getResule() {
if (getValue2() != 0) {
return getValue1() / getValue2();
}
throw new IllegalArgumentException("除数不能为零");
}
}
复制代码
public class OperationFactory {
public static Operation createOperation(String operation) {
Operation oper = null;
switch (operation) {
case "add":
oper = new OperationAdd();
break;
case "sub":
oper = new OperationSub();
break;
case "mul":
oper = new OperationMul();
break;
case "div":
oper = new OperationDiv();
break;
default:
throw new UnsupportedOperationException("不支持该操作");
}
return oper;
}
}
复制代码
public static void main(String[] args) {
Operation operationAdd = OperationFactory.createOperation("add")
operationAdd.setValue1(1)
operationAdd.setValue2(2)
System.out.println(operationAdd.getResule())
}
复制代码
工厂方法
public interface IFactory {
Operation CreateOption();
}
public class AddFactory implements IFactory {
public Operation CreateOption() {
return new OperationAdd();
}
}
public class SubFactory implements IFactory {
public Operation CreateOption() {
return new OperationSub();
}
}
public class MulFactory implements IFactory {
public Operation CreateOption() {
return new OperationMul();
}
}
public class DivFactory implements IFactory {
public Operation CreateOption() {
return new OperationDiv();
}
}
复制代码
public class Client {
public static void main(String[] args) {
//减法
IFactory subFactory = new SubFactory()
Operation operationSub = subFactory.CreateOption()
operationSub.setValue1(22)
operationSub.setValue2(20)
System.out.println("sub:"+operationSub.getResult())
//除法
IFactory Divfactory = new DivFactory()
Operation operationDiv = Divfactory.CreateOption()
operationDiv.setValue1(99)
operationDiv.setValue2(33)
System.out.println("div:"+operationSub.getResult())
}
}
复制代码