종속성 역전, IoC 및 DI 분석
NestJS의 종속성 주입 시스템을 탐색하면서 종속성 역전, 제어 역전 및 종속성 주입에 대해 더 자세히 알아볼 수 있었습니다. 이러한 개념은 유사해 보이지만 서로 다른 문제에 대한 고유한 솔루션을 제공합니다. 이 설명은 개인적으로 재충전의 역할을 하며, 이러한 용어와 씨름하는 다른 사람들에게 유용한 가이드가 되기를 바랍니다.
-
종속성 역전 원리(DIP)
정의: 상위 수준 모듈은 하위 수준 모듈에 의존해서는 안 됩니다. 둘 다 추상화에 의존해야 합니다. 추상화는 세부사항에 의존해서는 안 됩니다. 세부 사항은 추상화에 따라 달라집니다.
의미:
소프트웨어에서 상위 수준 모듈은 핵심 비즈니스 로직을 캡슐화하는 반면, 하위 수준 모듈은 특정 구현(데이터베이스, API 등)을 처리합니다. DIP가 없으면 상위 수준 모듈은 하위 수준 모듈에 직접 의존하므로 유연성을 방해하고 테스트 및 유지 관리를 복잡하게 하며 하위 수준 세부 사항을 교체하거나 확장하기 어렵게 만드는 긴밀한 결합을 생성합니다.
DIP는 이러한 관계를 역전시킵니다. 직접 제어하는 대신 상위 수준 모듈과 하위 수준 모듈 모두 공유 추상화(인터페이스 또는 추상 클래스)에 의존합니다.
DIP 없음
파이썬 예제
class EmailService: def send_email(self, message): print(f"Sending email: {message}") class Notification: def __init__(self): self.email_service = EmailService() def notify(self, message): self.email_service.send_email(message)
타입스크립트 예시
class EmailService { sendEmail(message: string): void { console.log(`Sending email: ${message}`); } } class Notification { private emailService: EmailService; constructor() { this.emailService = new EmailService(); } notify(message: string): void { this.emailService.sendEmail(message); } }
문제:
- 긴밀한 결합:
Notification
은EmailService
에 직접적으로 의존합니다. - 제한된 확장성:
SMSService
로 전환하려면Notification
을 수정해야 합니다.
DIP와 함께
파이썬 예제
from abc import ABC, abstractmethod class MessageService(ABC): @abstractmethod def send_message(self, message): pass class EmailService(MessageService): def send_message(self, message): print(f"Sending email: {message}") class Notification: def __init__(self, message_service: MessageService): self.message_service = message_service def notify(self, message): self.message_service.send_message(message) # Usage email_service = EmailService() notification = Notification(email_service) notification.notify("Hello, Dependency Inversion!")
타입스크립트 예시
interface MessageService { sendMessage(message: string): void; } class EmailService implements MessageService { sendMessage(message: string): void { console.log(`Sending email: ${message}`); } } class Notification { private messageService: MessageService; constructor(messageService: MessageService) { this.messageService = messageService; } notify(message: string): void { this.messageService.sendMessage(message); } } // Usage const emailService = new EmailService(); const notification = new Notification(emailService); notification.notify("Hello, Dependency Inversion!");
DIP의 장점:
- 유연성: 구현을 쉽게 교체할 수 있습니다.
- 테스트 가능성: 테스트를 위해 모의를 사용하세요.
- 유지관리성: 하위 수준 모듈의 변경 사항은 상위 수준 모듈에 영향을 주지 않습니다.
-
제어 반전(IoC)
IoC는 종속성 제어가 클래스 내에서 관리되지 않고 외부 시스템(프레임워크)으로 전환되는 설계 원칙입니다. 전통적으로 클래스는 종속성을 생성하고 관리합니다. IoC는 이를 뒤집습니다. 즉, 외부 엔터티가 종속성을 주입합니다.
Python 예: IoC 없음
class SMSService: def send_message(self, message): print(f"Sending SMS: {message}") class Notification: def __init__(self): self.sms_service = SMSService() # Dependency created internally def notify(self, message): self.sms_service.send_message(message)
TypeScript 예: IoC 없음
class SMSService { sendMessage(message: string): void { console.log(`Sending SMS: ${message}`); } } class Notification { private smsService: SMSService; constructor() { this.smsService = new SMSService(); // Dependency created internally } notify(message: string): void { this.smsService.sendMessage(message); } }
IoC가 없는 문제:
- 타이트한 커플링.
- 유연성이 낮습니다.
- 어려운 테스트.
Python 예제: IoC 사용
class EmailService: def send_email(self, message): print(f"Sending email: {message}") class Notification: def __init__(self): self.email_service = EmailService() def notify(self, message): self.email_service.send_email(message)
TypeScript 예: IoC 사용
class EmailService { sendEmail(message: string): void { console.log(`Sending email: ${message}`); } } class Notification { private emailService: EmailService; constructor() { this.emailService = new EmailService(); } notify(message: string): void { this.emailService.sendEmail(message); } }
IoC의 이점:
- 느슨한 커플링.
- 간단한 구현 전환.
- 테스트 가능성이 향상되었습니다.
-
의존성 주입(DI)
DI는 객체가 외부 소스로부터 종속성을 받는 기술입니다. 이는 다음을 통해 종속성을 주입하는 IoC의 실제 구현입니다.
- 생성자 주입
- 세터 주입
- 인터페이스 주입
Python 예제: DI 프레임워크(injector
라이브러리 사용)
from abc import ABC, abstractmethod class MessageService(ABC): @abstractmethod def send_message(self, message): pass class EmailService(MessageService): def send_message(self, message): print(f"Sending email: {message}") class Notification: def __init__(self, message_service: MessageService): self.message_service = message_service def notify(self, message): self.message_service.send_message(message) # Usage email_service = EmailService() notification = Notification(email_service) notification.notify("Hello, Dependency Inversion!")
TypeScript 예: DI 프레임워크(tsyringe
라이브러리 사용)
interface MessageService { sendMessage(message: string): void; } class EmailService implements MessageService { sendMessage(message: string): void { console.log(`Sending email: ${message}`); } } class Notification { private messageService: MessageService; constructor(messageService: MessageService) { this.messageService = messageService; } notify(message: string): void { this.messageService.sendMessage(message); } } // Usage const emailService = new EmailService(); const notification = new Notification(emailService); notification.notify("Hello, Dependency Inversion!");
DI의 장점:
- 단순화된 테스트.
- 확장성이 향상되었습니다.
- 유지보수성이 향상되었습니다.
이 자세한 설명은 DIP, IoC, DI 간의 관계와 차이점을 명확하게 설명하고 강력하고 유지 관리가 가능한 소프트웨어를 구축하는 데 있어 각 요소의 기여를 강조합니다.
위 내용은 종속성 역전, IoC 및 DI 분석의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











Linux 터미널에서 Python 버전을 보려고 할 때 Linux 터미널에서 Python 버전을 볼 때 권한 문제에 대한 솔루션 ... Python을 입력하십시오 ...

Fiddlerevery Where를 사용할 때 Man-in-the-Middle Reading에 Fiddlereverywhere를 사용할 때 감지되는 방법 ...

Python의 Pandas 라이브러리를 사용할 때는 구조가 다른 두 데이터 프레임 사이에서 전체 열을 복사하는 방법이 일반적인 문제입니다. 두 개의 dats가 있다고 가정 해

Uvicorn은 HTTP 요청을 어떻게 지속적으로 듣습니까? Uvicorn은 ASGI를 기반으로 한 가벼운 웹 서버입니다. 핵심 기능 중 하나는 HTTP 요청을 듣고 진행하는 것입니다 ...

Linux 터미널에서 Python 사용 ...

10 시간 이내에 컴퓨터 초보자 프로그래밍 기본 사항을 가르치는 방법은 무엇입니까? 컴퓨터 초보자에게 프로그래밍 지식을 가르치는 데 10 시간 밖에 걸리지 않는다면 무엇을 가르치기로 선택 하시겠습니까?

Investing.com의 크롤링 전략 이해 많은 사람들이 종종 Investing.com (https://cn.investing.com/news/latest-news)에서 뉴스 데이터를 크롤링하려고합니다.
