Interface Segregation Principle

Donghun Seol·2023년 4월 7일

아래와 같이 수륙양용차에 대한 인터페이스를 통째로 정의하지 않고,
자동차와 보트에 대한 인터페이스를 각각 정의한 후
수륙양용차를 구현해야할 경우에는 인터페이스 두개를 구현하면 된다.

interface ICar {
  drive: () => void;
  turnLeft: () => void;
  turnRight: () => void;
}

class Geneis implements ICar {
  drive() {}
  turnLeft() {}
  turnRight() {}
}

class Sonata implements ICar {
  drive() {}
  turnLeft() {}
  turnRight() {}
}

// 인터페이스를 너무 큰 개념으로 잡지 말라는 것
// 수륙양용차

interface IcarBoat {
  drive: () => void;
  turnLeft: () => void;
  turnRight: () => void;

  steer: () => void;
  steerLeft: () => void;
  steerRight: () => void;
}

// 수륙양용차의 인터페이스를 받아서 자동차 인스턴스를 생성하면
// 자동차에 필요없는 메서드까지 상속받게 되므로 부적절하다.
// 따라서 자동차인터페이스와 보트 인터페이스를 각각 정의한다.

interface IBoat {
  steer: () => void;
  steerLeft: () => void;
  steerRight: () => void;
}

// 만약 수륙양용차를 구현하고 싶으면 분리된 인터페이스 두개를 구현하면 된다.
class AmphibiousVehicle implements IBoat, ICar {
  drive() {}
  turnLeft() {}
  turnRight() {}

  steer() {}
  steerLeft() {}
  steerRight() {}
}

레퍼런스

https://www.youtube.com/watch?v=WBJm4U86m5k

profile
I'm going from failure to failure without losing enthusiasm

0개의 댓글