[OOP] 객체 지향 설계 5원칙(SOLID) : DIP(Dependency Inversion Principle)-의존 역전 원칙
DIP(Dependency Inversion Principle)
고수준 모듈은 저수준 모듈에 의존하지 않고 둘다 추상화에 의존해야 한다는 원칙
- 고수준 모듈 : 다른 클래스나 모듈을 사용하는 사용자 역할
- 저수준 모듈 : 구체적인 작업을 처리하는 세부사항이 담긴 클래스
이전 ISP(인터페이스 분리 원칙)에서 다루었던 것과 비슷하게 고수준 모듈이 저수준 모듈에 의존하지 않도록 추상화(인터페이스화)에 의존하도록 설계를 해야 한다는 말이다.
코드 예제
DIP가 적용되지 않은 코드
#include <string>
using namespace std;
class Monitor
{
public:
void display(const string& data)
{
//출력
}
};
class Keyboard
{
public:
string GetInput()
{
return "입력";
}
};
class Computer
{
private:
Keyboard keyboard;
Monitor monitor;
public:
void operate()
{
string input=keyboard.GetInput();
monitor.display(input);
}
};
위 코드에서 Computer 클래스는 Keyboard, Monitor 클래스와 강하게 결합되어 있어 Keyboard, Monitor가 종류가 다양해지면 코드에서 변경해야할 것들이 많아집니다.
DIP가 적용된 코드
#include <string>
using namespace std;
class InputDevice
{
public:
virtual string GetInput() = 0;
}
class OutputDevice
{
public:
virtual void display(const string& data) = 0;
}
class Monitor : public OutputDevice
{
public:
void display(const string& data) override
{
//출력
}
};
class Keyboard : public InputDevice
{
public:
string GetInput() override
{
return "입력";
}
};
class Computer
{
private:
InputDevice* inputDev;
OutputDevice* outputDev;
public:
Computer(InputDevice* input, OutputDevice* output)
: inputDev(input), outputDev(output){}
void operate()
{
string input=inputDev->GetInput();
outputDev->display(input);
}
};
클래스 상속과 오버라이딩을 적절히 활용해 Keyboard, Monitor와 Computer 사이에 인터페이스(추상화) 역할을 하는 클래스인 InputDevice, OutputDevice를 만들어 클래스 사이의 결합을 약하게 해주었기 때문에 해당 코드에서는 Keyboard, Monitor의 종류가 많아지더라도 새로운 클래스를 만들어 추가함으로써 간단하게 해결 가능합니다. 더불어 새로 추가되는 클래스도 InputDevice, OutputDevice를 상속하게 되어 해당 인터페이스 클래스를 통해 쉽게 이용 가능합니다.
ㅡ> 기존 코드 수정X, 확장(기능 추가)은 간단 ㅡ> OCP 준수
정리
이로써 SOLID 원칙 5개를 모두 알아보았다. 마지막 DIP의 내용을 보면 느끼지만 결국 SOLID 원칙이란 것은 객체지향 언어에서 객체를 활용하는 적절한 방법들을 제시하는 원칙들이었다. DIP의 내용도 결국 인터페이스 분리 원칙(ISP), 개방-폐쇄 원칙(OCP)을 준수하여 객체지향 언어의 장점을 발휘하고 코드 유지보수의 효율성을 향상시킬 수 있다는 것이다.
* 인터페이스 분리(ISP) ㅡ> 의존 역전 원칙(DIP) ㅡ> 확장에는 Open, 수정에는 Closed(OCP)
마무리
이전에는 전혀 신경 쓰지 않던 부분들이었지만 해당 원칙들을 공부하고 나서 코드를 작성하게 되니 아무래도 객체의 상속이나 구조에 대해 더 신경쓰게 되었고 아무래도 이러한 고민을 한번 거친 코드를 보면 확실히 이전과는 다르게 구조가 깔끔하다는 생각이 든다. 해당 원칙을 잘 준수하기 위해서 잘 활용해야 하는 것은 결국 '상속'이라는 객체지향 언어의 특징점이다. 앞으로도 원칙에 대해 한번 더 생각하고 설계 구조에 대해 고민하는 습관을 들이도록 하자.
참고사항
https://en.wikipedia.org/wiki/Dependency_inversion_principle
Dependency inversion principle - Wikipedia
From Wikipedia, the free encyclopedia Software programming object-oriented design methodology In object-oriented design, the dependency inversion principle is a specific methodology for loosely coupled software modules. When following this principle, the c
en.wikipedia.org
https://blog.itcode.dev/posts/2021/08/17/dependency-inversion-principle
[OOP] 객체지향 5원칙(SOLID) - 의존성 역전 원칙 DIP (Dependency Inversion Principle) - 𝝅번째 알파카의 개
의존성 역전 원칙이란 객체는 저수준 모듈보다 고수준 모듈에 의존해야한다는 원칙이다. 말이 좀 어렵다. 고수준 모듈은 뭐고, 저수준 모듈은 또 뭐란 말인가? 고/저수준 모델의 정의는 위와 같
blog.itcode.dev