定義:クライアントは、必要としないインターフェイスに依存してはなりません。あるクラスの別のクラスへの依存性は、最小のインターフェイスに確立する必要があります。
問題は次のとおりです。クラスAはインターフェイスIを介してクラスBに依存し、クラスCはインターフェイスIを通じてクラスDに依存します。インターフェイスIがクラスAとクラスBの最小インターフェイスではない場合、クラスBとクラスDは必要ありません。
解決策:肥大化したインターフェイスIをいくつかの独立したインターフェイスに分割し、クラスAとクラスCは、それぞれ必要なインターフェイスで依存関係を確立します。つまり、インターフェイス分離の原則が採用されています。
インターフェイスの分離の原理を説明する例を示しましょう。
The meaning of this figure is: Class A depends on methods 1, method 2, method 3 in interface I, and Class B is an implementation of dependence on class A. Class C depends on methods 1, method 4, method 5 in interface I, and Class D is an implementation of dependence on class C. For class B and D, although they both have unused methods (that is, methods marked with red fonts in the figure), since interface I is implemented, these unused methods must be implemented.
まず、インターフェイスの分離に違反した例を見てみましょう。
public Interface iWorker {public void work(); public void eat(); }パブリッククラスワーカーを実装Iworker {@Override public void work(){// todo worker work} @override public void eat(){// todo worker eat}} public class robot implection iworker {@override public void work(){// todo robot work} @override public void eat() }}
ロボットは食べる必要がないため、IWorkerは肥大化したインターフェイスと見なされます。もちろん、ロボットクラスでのEATメソッドの短期実装もできますが、これにより予測不可能なバグが発生する可能性があります。たとえば、EAT方法でランチボックスの数を消費する必要がある場合、誤った現象があります。
以下は、変更された実装です。
public Interface iWorker {public void work(); } public interface idiet {public void eat(); }パブリッククラスワーカーはiworker、idiet {@override public void work(){// todo work} @override public void eat(){// todo work}} public class robot implection iworker {@override public void work(){// todo robot work}}}}}}
要約:
1.インターフェイスは可能な限り小さく、非常にまとまりがある必要がありますが、適切で詳細すぎて維持するのが難しいはずです。
2.肥大化したインターフェイスとして設計されている場合、アダプターモードを使用して分離できます。