Object oriented language (객체지향설계) - DanielWorld/SoftwareTech GitHub Wiki

객체지향 5대 원칙 (SOLID)

TODO: 추후 정리 필요

1. Single Responsiblity Principle (단일 책임 원칙)

2. Open-Closed Principle (개방-패쇄 원칙)

  • 기존의 코드를 변경하지 않고(Closed) 기능을 수정하거나 추가할 수 있도록(Open) 설계해야 한다.
  • OCP에 만족하는 설계를 할 때 변경되는 것이 무엇인지에 초점을 맞춘다. 자주 변경되는 내용은 수정하기 쉽게 설계 하고, 변경되지 않아야 하는 것은 수정되는 내용에 영향을 받지 않게 하는 것이 포인트다. 이를 위해 자주 사용되는 문법이 인터페이스(Interface)이다
class Printer {
    fun print(contents: String): String {
        return "$contents - Naver"
    }
}

companion object fun main(args : IntArray) {
    val printer = Printer()
    printer.print("New documents!")
}

기존 Naver 에서 LINE 을 추가하도록 하는 요구사항이 왔을 때, Printer 의 print() 를 수정해야하는데, 자칫 OCP 원칙을 위배할 수 있다. 외부에서는 Printer().print() 를 의존하기 때문에, 가능하면 기존의 인터페이스를 유지하되 내부적으로 수정을 통해서 원하는 결과를 얻어야 한다.

class Printer {
    private lateinit signature: PrinterSignature    

    fun setSignature(signature : PrinterSignature) {
        this.signature = signature
    }

    fun print(contents: String): String {
        return this.signature.print(contents)
    }
}

interface PrinterSignature {
    fun print(contents: String) : String
}

class NaverSignature : PrinterSignatre {
    fun print(contents: String) : String {
        return "$contents - Naver"
    }
}

class LineSignature : PrinterSignatre {
    fun print(contents: String) : String {
        return "$contents - LINE"
    }
}

companion object fun main(args : IntArray) {
    val printer = Printer()
    printer.setSignature(NaverSignature())
    printer.setSignature(LineSignatuer())
    printer.print("New documents!")
}

인터페이스를 사용하여 동일한 동작 요청에 따라 다른 값을 리턴하도록 구현하였으며, 기존의 인터페이스를 해치지 않으면서 추가 입력만으로 문제가 해결된다. 이와 같은 설계를 디자인 패턴에서는 Strategy Pattern(전략 패턴)이라고 한다.

3. Liskov Substitution Principle (리스코프 치환 원칙)

4. Dependency Inversion Principle (의존 역전 원칙)

5. Interface Segregation Principle (인터페이스 분리 원칙)

출처: https://dev-momo.tistory.com/entry/SOLID-원칙 [Programming Note]