混乱を招くのはその通りで、実務では必要最小限の運用に留め、管理するクラスの数を3つ以内に収めるのがセオリーです
他方、多態勢との相性は良く、例えば図形クラスを継承する円、三角、四角の3つのクラスがあり、それぞれが面積を算出するareaと命名されたメソッドをオーバーライドする時
//図形
abstract class Sharp{
//面積
abstract double area();
}
//円
class Circle extends Sharp{
private final double diameter, //直径
radius; //半径
Circle(double diameter){
this.diameter=diameter;
this.radius=this.diameter/2;
}
double area(){
return radius*radius*3.14;
}
}
//三角
class Triangle extends Sharp{
private final double bottom, //底辺
height; //高さ
Triangle(double bottom,double height){
this.bottom=bottom;
this.height=height;
}
double area(){
return bottom*height/2;
}
}
//四角
class Square extends Sharp{
private final Triangle triangle;
Square(int bottom,int height){
this.triangle=new Triangle(bottom,height);
}
double area(){
return triangle.area()*2;
}
}
これらの図形の面積をまとめて取得したければ、反復的にareaを呼び出すことで目的を達成できます
public class Main {
public static void main(String[] args) throws Exception {
Sharp sharps[]={new Circle(10),new Triangle(10,10),new Square(10,10)};
String areaLogs[]=Arrays.stream(sharps).map(sharp-\u0026gt;Double.toString(sharp.area())).toArray(String[]::new);
System.out.println(String.join(\u0026quot;\
\u0026quot;,areaLogs));
}
}
/* 出力
78.5
50.0
100.0
*/
このように面積の計算という一意の目的に沿って各々の実装を分けるようなデザインパターンの基本をリスコフの置換原則と言います
この原則に則って設計されたクラスは運用面での安全が確約され、一括管理によるリスクの軽減を図れます