平时画UML图不太规范,如果有错误,欢迎大家指出
实现目标
用面向对象语言实现一个计算机控制台程序,要求输入两个数和运算符号,得到结果
思想
- 设计一个Operation接口,下面有4个具体的实现类(加减乘除),这是为了满足“单一职责原则”
- 业务类通过Fatory(工厂)调用Operatin的类,是为了满足“迪米特法则”,将业务(Main方法中)和计算方法(Operation接口)解耦合
UML图
代码
- Operation及其子类
package design.fatory;
public interface Operation {
Double getResult(Double a,Double b);
}
class Add implements Operation{
@Override
public Double getResult(Double a, Double b) {
return a + b;
}
}
class Mul implements Operation{
@Override
public Double getResult(Double a, Double b) {
return a * b;
}
}
class Div implements Operation{
@Override
public Double getResult(Double a, Double b) {
if(b == 0){
throw new RuntimeException("除数不能为0");
}
return a / b;
}
}
class Sub implements Operation{
@Override
public Double getResult(Double a, Double b) {
return a - b;
}
}
- 工厂方法
public class OperationFatory {
public Operation CreateOperate(char operate){
Operation operation = null;
switch (operate){
case '+':operation = new Add();break;
case '-':operation = new Sub();break;
case '*':operation = new Mul();break;
case '/':operation = new Div();break;
}
return operation;
}
}
- 业务类main方法
public static void main(String[] args){
Double a = 12d;
Double b = 0d;
OperationFatory operationFatory = new OperationFatory();
Operation operation = operationFatory.CreateOperate('/');
System.out.println(operation.getResult(a,b));
}
缺点
- 新增类时,需要修改OperationFatory工厂的判断方法,所以不符合“开放-封闭原则”
总结
- 如果我们系统中有许多类,这些类可以相互替换,那么此时我们就可以考虑是用工厂模式将他们管理起来,同时也可以和业务代码解耦
- 但我们有更好的模式,就是抽象工厂模式,让我一起期待吧!