본문 바로가기
객체지향 설계5대 원칙/PYTHON

객체지향5대원칙-ISP(Interface Segregation Principle) - 인터페이스 분리 원칙

by 쁘락지 2023. 5. 24.
반응형
객체지향 5대원칙(SOILD)의 원칙중 I에 해당하는것으로 다중 메소드를
가진 인터페이스가 있다면 여러개의 메소드로 분할 하는것이 합리적이다라고
말하고 있다.


그럼 예를들어보자
hwp파일이 있는데 이를 text와 html형태로 출력코자 한다면

구현클래스는 아래와 같이 하면 된다.

from abc import ABC,abstractmethod
class ConvertHwp(ABC):
    def gethtml(self):
        pass
    def gettext(self):
        pass

class Convert(ConvertHwp):

    def gethtml(self):
        print("html출력")

    def gettext(self):
        print("text출력")

if __name__ == "__main__":
    convert = Convert()
    convert.gethtml()
    convert.gettext()



여기서 특정 클래스에서 text만 출력하고 싶다면 어떻게 해야 할까?
그럼 위와 같이 했을때 문제점은 뭘까?
gettext()만 있으면 되는데 gethtml()라는 클라이언트가 필요로 하지 않는
메소드를 구현되어 있는것이다. 그래서 다음과 같이 변경한다.

from abc import ABC,abstractmethod
class Html(ABC):
    def gethtml(self):
        pass

class Text(ABC):
    def gettext(self):
        pass
   

class Convert(Text):

    def gettext(self):
        print("text출력")

if __name__ == "__main__":
    convert = Convert()
    convert.gettext()



만약 Text, Html이 다 필요하다면 어떻게 할까?
다음과 같이 하면 된다.
package kr.co.touch;

from abc import ABC,abstractmethod
class Html(ABC):
    def gethtml(self):
        pass

class Text(ABC):
    def gettext(self):
        pass


class Convert(Html, Text):

    def gethtml(self):
        print("html출력")

    def gettext(self):
        print("text출력")



if __name__ == "__main__":
    convert = Convert()
    convert.gethtml()
    convert.gettext()

이렇게 text, html을 출력하는 기능을 하나씩 분리해서 필요한 메소드가 있다면
그에 맞게끔 유지보수가 용이합니다. 이것이 이 정책을 쓰는 이유입니다.
반응형