简单工厂模式:
实例化对象的时候不再使用 new Object()形式,可以根据用户的选择条件来实例化相关的类。对于客户端来说,去除了具体的类的依赖。只需要给出具体实例的描述给工厂,工厂就会自动返回具体的实例对象。
使用场景:
//TODO
UML类图:
具体实现:
/**
* @ClassName Operation
* @Description 运算类
*/
public class Operation {
private double number1 = 0;
private double number2 = 0;
public double getNumber1() {
return number1;
}
public void setNumber1(double number1) {
this.number1 = number1;
}
public double getNumber2() {
return number2;
}
public void setNumber2(double number2) {
this.number2 = number2;
}
public double getResult() {
return 0;
}
}
/**
* @ClassName OperationAdd
* @Description 加法运算类
*/
public class OperationAdd extends Operation {
@Override
public double getResult() {
return getNumber1() + getNumber2();
}
}
/**
* @ClassName OperationSub
* @Description 减法运算类
*/
public class OperationSub extends Operation {
@Override
public double getResult() {
return getNumber1() - getNumber2();
}
}
/**
* @ClassName OperationFactory
* @Description 简单运算工厂类
*/
public class OperationFactory {
/**
* 生产运算对象
* @param operate 运算类型
* @return 运算对象
*/
public static Operation createOperate(String operate) {
Operation operation;
switch (operate) {
case "+":
operation = new OperationAdd();
break;
case "-":
operation = new OperationSub();
break;
default:
operation = null;
break;
}
return operation;
}
public static void main(String[] args) {
Operation operation = OperationFactory.createOperate("+");
operation.setNumber1(1);
operation.setNumber2(2);
System.out.print("运算结果:" + operation.getResult());
}
}