一.简介
实例化对象的时候不再使用 new Object()形式,可以根据用户的选择条件来实例化相关的类。对于客户端来说,去除了具体的类的依赖,降低了程序的耦合度。只需要给出具体实例的描述给工厂,工厂就会自动返回具体的实例对象。
二.实例介绍
1.设计一个简易计算器
功能描述:使用简单工厂设计模式来实现一个能进行加、减、乘、除运算的简单计算器
2.UML类图
3.代码如下:
运算接口
public interface Operation {
Double getResult(Double numberA, Double numberB);
}
加法类实现运算接口
public class OperationAdd implements Operation {
public Double getResult(Double numberA, Double numberB) {
return numberA + numberB;
}
}
减法类实现运算接口
public class OperationSub implements Operation {
public Double getResult(Double numberA, Double numberB) {
return numberA - numberB;
}
}
乘法类实现运算接口
public class OperationMul implements Operation {
public Double getResult(Double numberA, Double numberB) {
BigDecimal a1 = new BigDecimal(Double.toString(numberA));
BigDecimal b1 = new BigDecimal(Double.toString(numberB));
BigDecimal result = a1.multiply(b1);// 相乘结果
return result.doubleValue();
}
}
除法类实现运算接口
public class OperationDiv implements Operation {
private final int scale = 2; //保留小数位数
public Double getResult(Double numberA, Double numberB) {
try {
if (numberB == 0.0) throw new Exception("除数不能为0");
BigDecimal b1 = new BigDecimal(Double.toString(numberA));
BigDecimal b2 = new BigDecimal(Double.toString(numberB));
return b1.divide(b2,scale,BigDecimal.ROUND_HALF_UP).doubleValue();
} catch (Exception e) {
System.out.println("异常原因:"+e);
}
return null;
}
}
简单运算工厂类
public class OperationFactory {
public static Operation createOperate(String operate){
Operation operation = null;
if (operate.equals("+")){
operation = new OperationAdd();
}else if(operate.equals("-")){
operation = new OperationSub();
}else if(operate.equals("*")){
operation = new OperationMul();
}else if(operate.equals("/")){
operation = new OperationDiv();
}
return operation;
}
}
客户端测试代码如下:
public class Test {
public static void main(String[] args){
Operation operationAdd = OperationFactory.createOperate("+");
System.out.println("1.0+2.0="+operationAdd.getResult(1.0, 2.0));
System.out.println();
Operation operationSub = OperationFactory.createOperate("-");
System.out.println("2.5-1.0="+operationSub.getResult(2.5, 1.0));
System.out.println();
Operation operationMul = OperationFactory.createOperate("*");
System.out.println("12.5*2.3="+operationMul.getResult(12.5, 2.3));
System.out.println();
Operation operationDiv = OperationFactory.createOperate("/");
System.out.println("15.0/2.5="+operationDiv.getResult(15.37, 2.5));
System.out.println();
Operation operationDivException = OperationFactory.createOperate("/");
System.out.println("12.5/0.0="+operationDivException.getResult(12.5, 0.0));
}
}