public final class Hero {
private final Profession profession;
private final String name;
private final HairType hairType;
private final HairColor hairColor;
private final Armor armor;
private final Weapon weapon;
private Hero(Builder builder) {
this.profession = builder.profession;
this.name = builder.name;
this.hairColor = builder.hairColor;
this.hairType = builder.hairType;
this.weapon = builder.weapon;
this.armor = builder.armor;
}
}
빌더 패턴의 장점
1. 객체들마다 들어가야할 인자가 각각 다를 때 유연하게 사용할 수 있다.
2. 무조건 setter 생성을 방지하고 불변객체로 만들 수 있다.
3. 필수 argument를 지정할 수 있다.(보통의 경우, PK 역할을 할 Id 값이 될 것이다.)
Builder 패턴을 적용할 클래스
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@Builder(builderMethodName = "travelCheckListBuilder")
@ToString
public class TravelCheckList {
private Long id;
private String passport;
private String flightTicket;
private String creditCard;
private String internationalDriverLicense;
private String travelerInsurance;
public static TravelCheckListBuilder builder(Long id) {
if(id == null) {
throw new IllegalArgumentException("필수 파라미터 누락");
}
return travelCheckListBuilder().id(id);
}
}
public class MainClass {
public static void main(String[] args) {
// 빌더패턴을 통해 어떤 필드에 어떤 값을 넣어주는지 명확히 눈으로 확인할 수 있다!
TravelCheckList travelCheckList = TravelCheckList.builder(145L)
.passport("M12345")
.flightTicket("Paris flight ticket")
.creditCard("Shinhan card")
.internationalDriverLicense("1235-5345")
.travelerInsurance("Samsung insurance")
.build();
System.out.println("빌더 패턴 적용하기 : " + travelCheckList.toString());
}
// 결과
// 빌더 패턴 적용하기 : TravelCheckList(id=1, passport=M12345, flightTicket=Paris flight ticket, creditCard=Shinhan card, internationalDriverLicense=1235-5345, travelerInsurance=Samsung insurance)
}
@AllArgsConstructor(access = AccessLevel.PRIVATE) : @Builder 애노테이션을 선언하면 전체 인자를 갖는 생성자를 자동으로 만든다. @AllArgsConstructor는 전체 인자를 갖는 생성자를 만드는데, 접근자를 private으로 만들어서 외부에서 접근할 수 없도록 만든다.
@Builder : 위에서 설명했던 Builder 패턴을 자동으로 생성해주는데, builderMethodName에 들어간 이름으로 빌더 메서드를 생성해준다. 나같은 경우, 혼동을 줄이기 위해 클래스 명과 동일하게 놔두고 Builder로 선언했다.
클래스 내부 builder 메서드 : 필수로 들어가야할 필드들을 검증하기 위해 만들었다. 꼭 id가 아니라도 해당 클래스를 객체로 생성할 때 필수적인 필드가 있다면 활용할 수 있다.
'BackEnd' 카테고리의 다른 글
[Mybatis] resultMap collection을 이용한 중첩 데이터 출력하기 (2) | 2025.02.04 |
---|---|
Jenkins gradlew permission denied error (0) | 2022.04.01 |
Monolithic Architecture 그리고 MSA (0) | 2021.05.14 |
JAVA Map, List JQuery Implementation (0) | 2021.02.23 |
@Autowired @Resource @Inject (0) | 2020.09.02 |