개발/Spring(Hodol)

Spring, Java - Builder 패턴 분석

잇(IT) 2023. 9. 6. 11:08
728x90

- 결론부터 얘기하자면 Builder 패턴을 사용하게 되면, build() 메서드가 호출되기 전까지는 builder 클래스 안에 데이터가 저장되어 있다가 build() 메서드가 실행된 후에 해당 객체 필드에 값이 들어가게 된다.

 

- 아래 예를 통해 데이터 주입 과정을 알아 볼 것이다.

1. Post, PostEditor라는 엔티티가 생성되어 있다.

2. Post에는 아래와 같이 toEditor(), edti() 메서드가 작성되어 있다.

public PostEditor.PostEditorBuilder toEditor() {
        return PostEditor.builder()
                .title(title)
                .content(content);
    }
public void edit(PostEditor postEditor) {
        title = postEditor.getTitle();
        content = postEditor.getContent();
    }

3. PostEditor에는 아래와 같이 @Builder 어노테션이 디컴파일을 통해 생성된 코드가 추가되어 있다.

.....

    public PostEditor(String title, String content) {
        this.title = title;
        this.content = content;
    }

    public static PostEditorBuilder builder() {
        return new PostEditorBuilder();
    }

    public static class PostEditorBuilder {
        private String title;
        private String content;

        PostEditorBuilder() {
        }

        public PostEditorBuilder title(final String title) {
            if (title != null) {
                this.title = title;
            }
            return this;
        }

        public PostEditorBuilder content(final String content) {
            if (content != null) {
                this.content = content;
            }
            return this;
        }

        public PostEditor build() {
            return new PostEditor(this.title, this.content);
        }

        public String toString() {
            return "PostEditor.PostEditorBuilder(title=" + this.title + ", content=" + this.content + ")";
        }
    }
    
    .....

4. PostService 코드에는 아래와 같이 toEdit을 호출하는 코드와 builder 패턴을 이용해 PostEditor 객체를 생성하는 코드가 작성되어 있다.

.....

PostEditorBuilder editorBuilder = post.toEditor();

        PostEditor postEditor = editorBuilder.title(postEdit.getTitle())
                .content(postEdit.getContent())
                .build();
                
.....

- Builder 패턴 분석

- Builder 패턴을 분석하기 위해 아래와 같이 Test 코드를 실행한다.

1. DB에 title : BIS, content : 상도더샵의 데이터가 저장된 Post 엔티티가 있고, builder를 통해 생성된 title : null, content : 반포자이의 데이터가 저장된 postEdit 객체가 있다.

2. postService에 있는 edit() 메서드를 호출한다.

...

PostEditor.PostEditorBuilder editorBuilder = post.toEditor();

...

3. postService의 edit()메서드가 실행되면서, post.toEditor() 메서드가 실행된다.

4. 기존의 DB에서 불러온 Post 엔티티에 title : BIS, content : 상도더샵의 데이터가 저장되어 있었기 때문에  최초의 toEditor() 메서드에 의해 postEditor의 builder 클래스의 해당 필드에 값이 들어간다.

.....

public PostEditorBuilder title(final String title) {
            if (title != null) {
                this.title = title;
            }
            return this;
        }

        public PostEditorBuilder content(final String content) {
            if (content != null) {
                this.content = content;
            }
            return this;
        }
        
.....

5. 그 다음 postService에 있는 postEdit으로 넘어온 값을 통해 builder 패턴을 통한 editorBuilder에 저장되어 있는 데이터를 수정하는 코드를 실행한다.

.....

PostEditor postEditor = editorBuilder.title(postEdit.getTitle())
                .content(postEdit.getContent())
                .build();
                
.....

- builder 패턴이 실행됨에 따라 postEdit에 있던 데이터들이 builder 클래스의 메서드를 통해 builder 클래스의 필드에 값이 주입된다.

6. build() 메서드가 실행된 이후에

- builder 클래스의 필드에 있던 값들이 생성자 파라미터에 주입되면서 PostEditor 필드에 값이 입력되는 것을 확인 할 수 있다.

728x90