인터페이스 분리 원칙(Interface Segregation Principle, ISP)은 클라이언트가 자신이 사용하지 않는 메서드에 의존하지 않도록 하는 원칙입니다. 이는 인터페이스를 더 작고 구체적인 것으로 나누어 클라이언트가 자신에게 필요한 메서드만 사용하도록 설계해야 함을 의미합니다.
아래 예제에서는 큰 인터페이스를 사용하여 여러 클래스를 구현하는 상황을 보여줍니다.
public interface Worker {
void work();
void eat();
}
public class HumanWorker implements Worker {
@Override
public void work() {
System.out.println("Human working");
}
@Override
public void eat() {
System.out.println("Human eating");
}
}
public class RobotWorker implements Worker {
@Override
public void work() {
System.out.println("Robot working");
}
@Override
public void eat() {
// 로봇은 먹지 않음
throw new UnsupportedOperationException("Robots don't eat");
}
}
public class Main {
public static void main(String[] args) {
Worker human = new HumanWorker();
human.work();
human.eat();
Worker robot = new RobotWorker();
robot.work();
try {
robot.eat();
} catch (UnsupportedOperationException e) {
System.out.println(e.getMessage());
}
}
}
위의 예제에서는 RobotWorker 클래스가 eat 메서드를 지원하지 않기 때문에 UnsupportedOperationException을 던집니다. 이는 인터페이스 분리 원칙을 위반한 사례입니다.
ISP를 준수하기 위해, 인터페이스를 더 작고 구체적인 것으로 분리합니다.
public interface Workable {
void work();
}
public interface Eatable {
void eat();
}
public class HumanWorker implements Workable, Eatable {
@Override
public void work() {
System.out.println("Human working");
}
@Override
public void eat() {
System.out.println("Human eating");
}
}
public class RobotWorker implements Workable {
@Override
public void work() {
System.out.println("Robot working");
}
}
public class Main {
public static void main(String[] args) {
Workable humanWorker = new HumanWorker();
humanWorker.work();
((Eatable) humanWorker).eat();
Workable robotWorker = new RobotWorker();
robotWorker.work();
}
}
인터페이스 분리 원칙을 준수하면, 인터페이스가 더 작고 구체적이 되어 클래스가 자신에게 필요한 메서드만 구현하게 할 수 있습니다. 이는 코드의 복잡도를 줄이고, 유지보수성과 확장성을 향상시킵니다. 따라서 소프트웨어 개발에서 ISP를 준수하는 것이 중요합니다.