JAVA · 디자인패턴
레이어드 아키텍처
전통적인 3계층 아키텍처의 구조와 의존성 흐름입니다.
디자인패턴중급레이어드3계층ControllerService
핵심 설명
전통적인 3계층 아키텍처의 구조와 의존성 흐름입니다.
Java code
// 1. 프레젠테이션 계층 (Controller)
class UserController {
private final UserService2 service;
UserController(UserService2 service) { this.service = service; }
String handleGetUser(String id) {
UserDTO dto = service.getUser(id);
return "{\"name\":\"" + dto.name() + "\"}";
}
}
// 2. 비즈니스 계층 (Service)
record UserDTO(String id, String name, String email) {}
class UserService2 {
private final UserDAO dao;
UserService2(UserDAO dao) { this.dao = dao; }
UserDTO getUser(String id) {
UserEntity entity = dao.findById(id);
if (entity == null) throw new RuntimeException("사용자 없음");
return new UserDTO(entity.id, entity.name, entity.email);
}
}
// 3. 데이터 접근 계층 (DAO/Repository)
class UserEntity {
String id, name, email;
UserEntity(String id, String name, String email) {
this.id = id; this.name = name; this.email = email;
}
}
class UserDAO {
UserEntity findById(String id) {
return new UserEntity(id, "홍길동", "hong@test.com");
}
}
class Main {
public static void main(String[] args) {
UserDAO dao = new UserDAO();
UserService2 service = new UserService2(dao);
UserController controller = new UserController(service);
System.out.println(controller.handleGetUser("1"));
}
}학습 팁
각 계층은 바로 아래 계층에만 의존해야 합니다. Controller가 DAO를 직접 호출하면 계층 위반입니다.
주의할 점
Entity를 Controller에서 직접 반환하면 DB 스키마 변경이 API에 영향을 줍니다. 반드시 DTO로 변환하세요.
자주 묻는 질문
레이어드 아키텍처란 무엇인가요?
전통적인 3계층 아키텍처의 구조와 의존성 흐름입니다.
레이어드 아키텍처 학습 시 주의할 점은 무엇인가요?
Entity를 Controller에서 직접 반환하면 DB 스키마 변경이 API에 영향을 줍니다. 반드시 DTO로 변환하세요.
Continue Learning
Java 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.