의존
클래스가 다른 클래스를 의존한다는 것은 한 클래스가 다른 클래스의 기능이나 서비스를 사용하거나 필요하다는 의미이다.
의존성
의존성은 특정 클래스가 기능을 수행하기 위해 필요로 하는 다른 클래스, 즉 필요한 클래스이다
의존성 주입 전 ( 강한 결합 , tight-coupling )
cashService 와 productService 인스턴스를 클래스 안에서 생성해서 사용하고 있다.
이렇게 하면 만약 이 서비스들을 다른 서비스로 교체하려면? 모든 service가 쓰인 곳을 찾아가 하나씩 바꿔야 한다. ( 유지보수 꽝 )
import { CashService} from './services/cash.service'
import {ProductService} from './services/product.service'
class ProductController {
buyProduct = (req,res)=>{
// 1. 가진 돈 검증하는 코드 ( 대략 10줄 정도 )
const cashService = new CashService()
const hasMoney = cashService.checkValue()
// 2. 판매여부 검증하는 코드 ( 대략 10줄 정도 )
const productService = new ProductService()
const isSoldout = productService.checkSoldout()
// 3. 상품 구매하는 코드
// if(hasMoney && !isSoldout) {
// res.send(" 상품 구매 완료 ")
// }
}
refundProduct = (req,res)=>{
// 1. 판매여부 검증하는 코드 ( 대략 10줄 정도 )
const productService = new ProductService()
const isSoldout = productService.checkSoldout()
// 2. 상품 환불하는 코드
if(isSoldout){
res.send(" 상품 환불 완료 ")
}
}
}
의존성 주입 후 ( 느슨한 결합 , loose-coupling )
컨트롤러 밖에서 인스턴스를 생성후 , 매개변수를 통해서 서비스 인스턴스를 가져와서 사용한다.
이렇게 바꾸면 코드의 재사용성을 높일 수 있다.
RAM 에 매번 같은 클래스의 인스턴스를 생성하지 않아도 되므로 메모리 절약도 된다. ( 싱글톤 패턴 구현 가능 )
모든 의존성 주입이 싱글톤 패턴은 아니다 ! 싱글톤 패턴으로 구현하지 않을 수도 있다.
또 의존성 주입을 사용하지 않더라도 생성자 함수를 통해서 싱글톤 패턴을 구현할수도 있다.
// index.js 파일 ( module 역할 )
import { CashService } from './mvc/controllers/services/cash.service.js'
import {ProductService} from "./mvc/controllers/services/product.service.js"
const cashService = new CashService();
const productService = new ProductService();
const productController = new ProductController(cashService, productService);
// product.controller.js 파일
import { CashService} from './services/cash.service'
import {ProductService} from './services/product.service'
class ProductController {
cashService
productService
constructor(cashService,productService){
this.cashService = cashService;
this.productService = productService;
}
buyProduct = (req,res)=>{
// 1. 가진 돈 검증하는 코드 ( 대략 10줄 정도 )
const hasMoney = this.cashService.checkValue()
// 2. 판매여부 검증하는 코드 ( 대략 10줄 정도 )
const isSoldout = this.productService.checkSoldout()
}
제어의 역전 , IoC ( inversion of Control )
위의 예시에서는 Controller에 필요한 서비스 클래스들을 직접 넣어줬다.
Nest.js 에서는 이역할을 대신 해주는 기능이 있다. IoC 컨테이너 이다.
728x90
'Backend 백엔드' 카테고리의 다른 글
[ 35 ] MVC 패턴 실습 (0) | 2024.08.22 |
---|---|
[ 34 ] 객체지향 프로그래밍 (0) | 2024.08.22 |
[ 33 ] Class 실습 ! const 안붙이네? (1) | 2024.08.22 |
[ 32 ] 오픈그래프 스크랩핑 (0) | 2024.08.21 |
[ 31 ] 스크래핑과 브라우저 주소창의 원리 (0) | 2024.08.21 |