본문 바로가기
반응형
Design Pattern/Design Pattern(eng)

Why & How to use Builder Pattern, good things

by brightGarden02 2022. 11. 27.

Why use Builder Pattern

: Making constructor is cumbersome.

When collaborating with other developers, multiple constructors can lead to confusion about which constructor to use.

Even if made constructor, some values could be null. It is cumbersome to put null.

 

 

Builder Pattern's Good things:

It is easy to make constructor.

You don't have to think what values' order, neither what values to put

 

 

Builder Pattern's Bad things:

Looks none

 

 

How to use Builder Pattern(In Spring)

1. Setting lombok

2. Use annotatin @SuperBuilder

Why used @SuperBuilder. Not @Builder

-> to make extended entity

-> to put parent entity values

@Entity
@Getter
@AllArgsConstructor
@NoArgsConstructor
@SuperBuilder
public class Chef extends BaseEntity {

    private ChefRole chefRole;
    private FoodCategory foodCategory;

    @OneToMany(mappedBy = "chef")
    private List<Menu> menuList = new ArrayList<>();

}

 

 

Also write @SuperBuilder in parent entity

@SuperBuilder
@Getter
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public abstract class BaseEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column
    private Long id;

    @CreatedDate
    private LocalDateTime createDate;

    @LastModifiedDate
    private LocalDateTime modifyDate;
}

 

 

Used builder to create object in Client Class

private static void createKoreanChef() {
   Chef chef = Chef.builder()
         .chefRole(ChefRole.한식요리사)
         .foodCategory(FoodCategory.한식)
         .build();
   chefList.add(chef);
}

댓글


반응형
반응형