SW 구조/디자인패턴
DTO 디자인패턴
tacoyaggi
2023. 11. 8. 13:55
주제
- DTO 무엇이고 DTO 디자인 패턴의 특징에 대해서 알아보자.
개념
- Data Transfer Object
- 데이터를 객체로 전달하기 위한 디자인 패턴
- 클라이언트 - 서버 간의 통신에서 DTO를 사용하면 데이터를 효율적으로 전송 가능
코드
- Request 객체 (파라미터)
- Response 객체 (return 객체)
RequestDTO 함수 중 파라미터에서 DTO 객체를 사용함
Service 단계로 객체를 넘길 때도 DTO 객체를 사용함
Service 단계에서 return 받은 Entity 객체의 값을 DTO 객체로 변경하여 Client에게 return
public class GuestbookController : Controller
{
private readonly GuestbookService _guestbookService;
public GuestbookController(GuestbookService guestbookService)
{
_guestbookService = guestbookService;
}
public IActionResult Index()
{
return View();
}
public async Task<IActionResult> RequestDTO(GuestbookDTO dtoParam)
{
GuestbookDTO responseDto = new GuestbookDTO();
var result = await _guestbookService.GetGuestBook(dtoParam);
responseDto.title = result.title;
responseDto.content = result.content;
return View(responseDto);
}
}
Service 단계에서는 ORM을 사용해야하기 때문에 Entity 객체를 사용함
Service 단계의 return 또한 Entity 객체임
public class GuestbookService
{
private readonly DbContext _dbContext;
public GuestbookService(DbContext dbContext)
{
_dbContext = dbContext;
}
public async Task<GuestBook> GetGuestBook(GuestbookDTO dtoPram)
{
using IDbConnection db = _dbContext.GetConnection();
return await db.QueryFirstAsync<GuestBook>("GetGuestBook_SP",commandType:CommandType.StoredProcedure);
}
}
정리
- DTO 객체는 클라이언트 - 서버간 통신에 있어서 Request , Response 객체이다.
- ORM 사용을 위해 비지니스 로직 단계에서는 DTO → Entity 변경이 필요 하다.
- 반대로 Reponse 단계에서는 Entity → DTO 변경이 필요하다.
- 필요한 데이터만 전달 가능하기에 DTO 디자인 패턴은 효율적이다.
- 객체 타입 변환 단계는 Service가 될 수 있고 Controller가 될 수 있음 상황에 따라 변경하도록