「介面隔離、多態替換、繼承復用」是物件導向三大支柱。本文通過一個計算三角形與矩形面積/周長的完整案例,示範如何將這三大機制有機結合,構建可擴展的幾何計算體系。
public interface Shape {
double area(); // 面積
double perimeter(); // 周長
}
public class Triangle implements Shape {
private final double a, b, c;
public Triangle(double a, double b, double c) {
if (!isValid(a, b, c))
throw new IllegalArgumentException("邊長無法構成三角形");
this.a = a; this.b = b; this.c = c;
}
private boolean isValid(double a, double b, double c) {
return a + b > c && a + c > b && b + c > a;
}
@Override public double perimeter() { return a + b + c; }
@Override public double area() {
double p = perimeter() / 2;
return Math.sqrt(p * (p - a) * (p - b) * (p - c)); // 海倫公式
}
}
public class Rectangle implements Shape {
private final double width, height;
public Rectangle(double width, double height) {
this.width = width; this.height = height;
}
@Override public double perimeter() { return 2 * (width + height); }
@Override public double area() { return width * height; }
}
public class GeometryDemo {
public static void main(String[] args) {
Shape[] shapes = {
new Triangle(3, 4, 5),
new Rectangle(10, 20),
new Triangle(6, 8, 10)
};
for (Shape s : shapes) {
System.out.printf("%s: 面積=%.2f, 周長=%.2f%n",
s.getClass().getSimpleName(), s.area(), s.perimeter());
}
// 輸出:
// Triangle: 面積=6.00, 周長=12.00
// Rectangle: 面積=200.00, 周長=60.00
// Triangle: 面積=24.00, 周長=24.00
}
}
Comparable<Shape> 按面積排序Stream API 計算總面積:Arrays.stream(shapes).mapToDouble(Shape::area).sum()Visitor 模式支援導出 SVG/JSON 等多種格式這個小案例浓縮了「面向介面編程、封裝驗證、不可變設計、多態分發、開閉原則」五大核心技能。實際專案中,將業務規則封裝在領域模型建構子中,配合介面驅動架構,能顯著降低耦合、提升可測試性與擴展性。