빌더 패턴(Builder Pattern)은 객체 생성을 간단하게 만들어주는 패턴 중 하나입니다. 자바에서 빌더 패턴을 구현할 때에는, 객체 생성에 필요한 데이터들을 설정하는 메서드들을 제공하고, 최종적으로 build() 메서드를 호출하여 객체를 생성하는 방식으로 구현합니다.
예를 들어, 책(Book) 객체를 생성할 때 필요한 제목(title), 저자(author), 출판사(publisher), 출판일(publishedDate) 등의 데이터를 빌더 패턴으로 구현할 수 있습니다. 아래는 자바로 구현한 책 빌더 패턴 예시입니다.
Book 클래스:
public class Book {
private String title;
private String author;
private String publisher;
private LocalDate publishedDate;
private Book(BookBuilder builder) {
this.title = builder.title;
this.author = builder.author;
this.publisher = builder.publisher;
this.publishedDate = builder.publishedDate;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public String getPublisher() {
return publisher;
}
public LocalDate getPublishedDate() {
return publishedDate;
}
public static class BookBuilder {
private String title;
private String author;
private String publisher;
private LocalDate publishedDate;
public BookBuilder setTitle(String title) {
this.title = title;
return this;
}
public BookBuilder setAuthor(String author) {
this.author = author;
return this;
}
public BookBuilder setPublisher(String publisher) {
this.publisher = publisher;
return this;
}
public BookBuilder setPublishedDate(LocalDate publishedDate) {
this.publishedDate = publishedDate;
return this;
}
public Book build() {
return new Book(this);
}
}
}
위 코드에서 Book 클래스는 private 생성자를 가지며, 빌더 클래스(BookBuilder)를 내부 클래스로 가지고 있습니다. 빌더 클래스는 각 필드들을 설정하는 메서드(setTitle(), setAuthor() 등)와 build() 메서드를 가지며, build() 메서드에서 최종적으로 Book 객체를 생성합니다.
아래는 이를 활용한 Book 객체 생성 코드입니다.
Book book = new Book.BookBuilder()
.setTitle("Effective Java")
.setAuthor("Joshua Bloch")
.setPublisher("Addison-Wesley Professional")
.setPublishedDate(LocalDate.of(2018, 12, 14))
.build();
위 코드에서 BookBuilder 클래스를 이용하여 제목, 저자, 출판사, 출판일 등을 설정한 후, build() 메서드를 호출하여 Book 객체를 생성합니다. 이렇게 하면 객체 생성 시 각 필드들이 빠짐없이 설정될 수 있으며, 가독성도 높아집니다.
빌더 패턴을 사용하면 생성자에 많은 매개변수를 전달하지 않고, 각각의 메서드로 필요한 데이터를 설정할 수 있으므로 코드 유지보수성도 좋아지고, 가독성도 높아집니다. 또한, 빌더 패턴을 사용하면 불변 객체(Immutable Object)를 생성할 수 있습니다. 이는 멀티스레드 환경에서 안전하며, 예기치 않은 값 변경을 막아줍니다.
빌더 패턴은 자바뿐만 아니라 다른 객체 지향 언어에서도 사용됩니다. 또한, lombok과 같은 라이브러리를 사용하면 빌더 패턴을 보다 쉽게 구현할 수 있습니다.
'JAVA > GOF Design Pattern' 카테고리의 다른 글
GOF 브릿지 패턴 (0) | 2023.05.09 |
---|---|
GOF 중재자(Mediator) 패턴 (0) | 2023.05.09 |
GOF 스트레티지 패턴(Strategy Pattern) (0) | 2023.05.09 |
GOF Observer Pattern (0) | 2023.05.09 |
GOF Abstract Factory Pattern (0) | 2023.05.08 |