Open-Close Principle,OCP
π = 3.14
。
π
值取的精度对于某些场景是不足的,需要扩展。design-1.1-1
|——src
|——main
|--java
|--com.lino.design
|--impl
| |--CalculationArea.java
| |--CalculationAreaExt.java
|--ICalculationArea.java
|——test
|--java
|--com.lino.design.test
|--ApiTest.java
ICalculationArea.java
package com.lino.design;
/**
* @description: 面积计算接口
*/
public interface ICalculationArea {
/**
* 计算面积,长方形
*
* @param x 长
* @param y 宽
* @return 面积
*/
double rectangle(double x, double y);
/**
* 计算面积,三角形
* 海伦公式:S=√[p(p-a)(p-b)(p-c)] 其中:p=(a+b+c)/2
*
* @param x 边长x
* @param y 边长y
* @param z 边长z
* @return 面积
*/
double triangle(double x, double y, double z);
/**
* 计算面积,圆形
* 圆面积公式:S=πr²
*
* @param r 半径
* @return 面积
*/
double circular(double r);
}
S=√[p(p-a)(p-b)(p-c)]
,其中 p=(a+b+c)/2
。S=πr²
CalculationArea.java
package com.lino.design.impl;
import com.lino.design.ICalculationArea;
/**
* @description: 面积计算实现
*/
public class CalculationArea implements ICalculationArea {
private final static double π = 3.14D;
@Override
public double rectangle(double x, double y) {
return x * y;
}
@Override
public double triangle(double x, double y, double z) {
double p = (x + y + z) / 2;
return Math.sqrt((p - x) * (p - y) * (p - z));
}
@Override
public double circular(double r) {
return π * r * r;
}
}
rectangle
)、三角形(triangle
)、圆形(circular
)。
π
值取的是 3.14D
,这也是要扩展精度的方法和体现开闭原则的地方。π
值计算出的圆形面积本可以满足需求,但是因为精度加长破坏了原有精度下的稳定性。CalculationArea.java
package com.lino.design.impl;
import com.lino.design.ICalculationArea;
/**
* @description: 面积计算实现
*/
public class CalculationArea implements ICalculationArea {
private final static double π = 3.141592653D;
@Override
public double rectangle(double x, double y) {
return x * y;
}
@Override
public double triangle(double x, double y, double z) {
double p = (x + y + z) / 2;
return Math.sqrt((p - x) * (p - y) * (p - z));
}
@Override
public double circular(double r) {
return π * r * r;
}
}
CalculationAreaExt.java
package com.lino.design.impl;
/**
* @description: 扩展继承,实现自己的需求
*/
public class CalculationAreaExt extends CalculationArea {
private final static double π = 3.141592653D;
@Override
public double circular(double r) {
return π * r * r;
}
}
ApiTest.java
@Test
public void test_calculationAreaExt() {
ICalculationArea area = new CalculationAreaExt();
double circular = area.circular(10);
System.out.println(circular);
}
测试结果
314.1592653