Home Builder Design Pattern
Post
Cancel

Builder Design Pattern

Builder Design Pattern

상대적으로 복잡한 객체생성을 다루는 패턴중 하나 또다른 객체를 사용하여 객체를 생성하기 위한 객체화 과정을 분리

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
public class BankAccount {
    
    private String name;
    private String accountNumber;
    private String email;
    private boolean newsletter;

    // constructors/getters
    
    public static class BankAccountBuilder {
        // builder code
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public static class BankAccountBuilder {
    
    private String name;
    private String accountNumber;
    private String email;
    private boolean newsletter;
    
    public BankAccountBuilder(String name, String accountNumber) {
        this.name = name;
        this.accountNumber = accountNumber;
    }

    public BankAccountBuilder withEmail(String email) {
        this.email = email;
        return this;
    }

    public BankAccountBuilder wantNewsletter(boolean newsletter) {
        this.newsletter = newsletter;
        return this;
    }
    
    public BankAccount build() {
        return new BankAccount(this);
    }
}
1
2
3
4
5
BankAccount newAccount = new BankAccount
  .BankAccountBuilder("Jon", "22738022275")
  .withEmail("jon@example.com")
  .wantNewsletter(true)
  .build();

언제 Builder pattern을 사용할 것인가?

  1. 객체를 생성하는 과정이 매우 복잡할경우 (필수.옵션 파라미터들이 너무 많을경우)

  2. 생성자 파라미터의 수의 증가가 생성자 리스트수도 증가시킬 경우

출처

https://www.baeldung.com/creational-design-patterns#builder

This post is licensed under CC BY 4.0 by the author.

Logical Replication

Rollup Jobs

Comments powered by Disqus.

Trending Tags