์Šคํ”„๋ง

[์Šคํ”„๋ง] ๋นŒ๋” ํŒจํ„ด @Builder

HHRR 2024. 1. 23. 18:21

1. ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜๋Š” ๋ฐฉ๋ฒ•

๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜๋Š” ๋ฐฉ๋ฒ•์—๋Š” ๋Œ€ํ‘œ์ ์œผ๋กœ ๋‹ค์Œ๊ณผ ๊ฐ™์€ 3๊ฐ€์ง€๊ฐ€ ์žˆ๋‹ค.

  1. ์ƒ์„ฑ์ž ํŒจํ„ด
    User user = new User("์œ ์ €1", "1234"); 
    userRepository.save(user);
  2. ์ž๋ฐ”๋นˆ์ฆˆ ํŒจํ„ด 
    1. User user = new User(); user.setUserId("์œ ์ €1"); user.setUserPassword("1234"); userRepository.save(user);
  3. ๋นŒ๋” ํŒจํ„ด
    User user = User.builder()
                    .userId("์œ ์ €1")
                    .userPassword("1234")
                    .build();
    
        userRepository.save(user);

2. ๋นŒ๋” ํŒจํ„ด(Builder Pattern)์ด๋ž€?

๋นŒ๋”ํŒจํ„ด์€ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜๋Š” ๋ฐฉ๋ฒ• ์ค‘ ํ•˜๋‚˜์ด๋‹ค.

๊ฐ์ฒด๋ฅผ ์ •์˜ํ•˜๊ณ  ๊ทธ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•  ๋•Œ ๋ณดํ†ต ์ƒ์„ฑ์ž๋ฅผ ํ†ตํ•ด ์ƒ์„ฑํ•˜๋Š” ๊ฒƒ์„ ์ƒ๊ฐํ•˜๋Š”๋ฐ, ๋งค๊ฐœ๋ณ€์ˆ˜๊ฐ€ ๋งŽ์•„์งˆ์ˆ˜๋ก ๋งŽ์€ ์กฐํ•ฉ๊ณผ ์ƒ์„ฑ์ž์˜ ์ˆ˜๊ฐ€ ๋งŽ์•„์ง„๋‹ค๋Š” ๋“ฑ์˜ ๋‹จ์ ์ด ์žˆ๋‹ค.

๊ทธ๋ž˜์„œ ๊ฐ์ฒด ์ƒ์„ฑํ•  ์ˆ˜ ์žˆ๋Š” ๋นŒ๋”๋ฅผ builder() ํ•จ์ˆ˜๋ฅผ ํ†ตํ•ด ์–ป๊ณ , ๊ฑฐ๊ธฐ์— ์„ธํŒ…ํ•˜๊ณ ์žํ•˜๋Š” ๊ฐ’์„ ์„ธํŒ…ํ•˜์—ฌ .builder()๋ฅผ ์ž‘๋™์‹œ์ผœ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•œ๋‹ค.

์žฅ์ 

  1. ์ƒ์„ฑ์ž ํŒŒ๋ผ๋ฏธํ„ฐ๊ฐ€ ๋งŽ์„ ๊ฒฝ์šฐ์— ๊ฐ€๋…์„ฑ์ด ์ข‹์ง€ ์•Š์€๋ฐ, ๋นŒ๋” ํŒจํ„ด์€ ๊ฐ ๊ฐ’๋“ค์˜ ์ด๋ฆ„ ํ•จ์ˆ˜๋กœ ์…‹ํŒ…๋˜์–ด ๊ฐ๊ฐ ๋ฌด์Šจ ๊ฐ’์„ ์˜๋ฏธํ•˜๋Š”์ง€ ํŒŒ์•…์ด ์‰ฝ๋‹ค
  2. ์ˆœ์„œ๊ฐ€ ์ƒ๊ด€์—†๋‹ค

3. @Builder

๋”ฐ๋ผ์„œ ์ด ์–ด๋…ธํ…Œ์ด์…˜์€ ๋นŒ๋”ํŒจํ„ด์œผ๋กœ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•ด์ฃผ๋Š” ์–ด๋…ธํ…Œ์ด์…˜์ด๋‹ค.

setter๊ฐ€ ์—†๊ธฐ ๋•Œ๋ฌธ์— ๊ฐ์ฒด์˜ ๋ถˆ๋ณ€์„ฑ์„ ๋ณด์žฅํ•˜๋ฉฐ ๋ฐ์ดํ„ฐ์˜ ์ผ๊ด€์„ฑ์„ ์œ ์ง€ํ•  ์ˆ˜ ์žˆ๋‹ค.

๋นŒ๋”ํŒจํ„ด์„ ์ ์šฉํ•  ๊ฐ์ฒด์— @Builder ์–ด๋…ธํ…Œ์ด์…˜์„ ๋‹ฌ๋ฉด ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•  ์ˆ˜ ์žˆ๋‹ค.

@Builder
public class User{
  private String userPassword;
  private String userId;
}
User user = User.builder()
                .userId("์œ ์ €1")
                .userPassword("1234")
                .build();

    userRepository.save(user);

 

 

์ถœ์ฒ˜

https://projectlombok.org/features/Builder

https://pamyferret.tistory.com/67