Definition: A client should not rely on interfaces that it does not need; A class's dependency on another class should be based on the smallest interface.
The problem is: Class A relies on Class B via interface I, Class C through interface I-dependent Class D, if interface I is not a minimum interface for Class A and Class B, then Class B and Class D have to implement the methods they do not need.
Solution: Split the bloated interface I into several separate interfaces, and Class A and Class C are dependent on the interfaces they need. That is to adopt the principle of interface isolation.
For example, the principle of interface isolation:
The meaning of this diagram is: Class A relies on interface I, Method 1, Method 2, Method 3, and Class B is the implementation of Class A dependency. Method 1, Method 4, method 5 in Class C dependency interface I, and Class D are implementations of Class C dependencies. For Class B and Class D, although they all have methods that are not in use (that is, the red font tag in the diagram), they also have to implement the methods that are not available because they implement interface I.
Let's first look at an example of a violation of interface isolation:
Public interface IWorker {public
void work ();
public void Eat ();
}
Public class worker implements iworker{
@Override public
void work () {
//TODO worker work
}
@Override The public
Void Eat () {
//TODO worker Eats
}} public
class Robot implements IWorker {
@Override c16/>public void Work () {
/todo robot work
}
@Override public
void Eat () {
//todo robot eat?
}
}
Because the robot does not need to eat, so iworker is considered a bloated interface, of course, you can also in the robot class eat method short implementation, but this may produce unpredictable bugs, such as Eat method needs to consume the number of boxes, there will be no corresponding phenomenon.
Here is the modified implementation:
Public interface IWorker {public
void work ();
}
Public interface Idiet {public
void eat ();
}
Public class worker implements IWorker, idiet{
@Override public
void work () {
//TODO worker work
}
@ Override public
void Eat () {
//TODO worker eat
}
} public
class Robot implements IWorker {
@ Override public
void work () {
//TODO robot work
}
}
Summarize:
1. The interface should be as small as possible, and high cohesion, but to be appropriate, too detailed and difficult to maintain.
2. If you have designed a bloated interface, you can isolate it using the adapter pattern.