ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Java] 빌더패턴 Builder Pattern
    Java 2016. 11. 5. 23:04

    빌더패턴


    필드가 많은 객체를 생성할 경우 생성자를 이용하면 다루기 어렵고 헷갈릴 수 있다.

    public class Pet {
    private final Animal animal;
    private final String petName;
    private final String ownerName;
    private final String address;
    private final String telephone;
    private final String emailAddress; //선택사항
    private final Date dateOfBirth; //선택사항
    }

    Pet 객체를 만들려면 필요한 모든 필드와 조합할 수 있는 옵션 필드를 포함하도록 매개변수를 갖는 생성자가 4개 이상 필요하다.

    여기에 더 많은 옵션이 생긴다면 관리하기가 무척 어려워 질 것이다.


    해결 방법 1 - 자바빈즈 패턴

    final 키워드를 제거하고 Setter를 사용할 수 있다. 단 유효하지 않은 Pet 객체를 생성할 수 있다는 점에 주의해야 한다. 

    final Pet p = new Pet();
    p.setEmailAddress("test@test.com");


    해결 방법 2 - 빌더 패턴

    빌더 패턴은 원하는 객체를 바로 생성하는 대신 클라이언트는 모든 필수 매개변수를 갖는 생성자(또는 static 팩토리 메소드)를 호출하여 빌더 객체를 얻고 그 다음에 빌더 객체의 세터 메소드를 호출하여 필요한 선택 매개변수들의 값을 설정해주는 방식이다.

    public class Pet {
    public static class Builder {
    private String animal;
    private String petName;
    private String ownerName;
    private String address;
    private String telephone;
    private Date dateOfBirth; //선택사항

    private String emailAddress; //선택사항


    public Builder withAnimal(final String animal) {
    this.animal = animal;
    return this;
    }

    public Builder withPetName(final String petName) {
    this.petName = petName;
    return this;
    }

    public Builder withOwnerName(final String ownerName) {
    this.ownerName = ownerName;
    return this;
    }

    public Builder withAddress(final String address) {
    this.address = address;
    return this;
    }

    public Builder withEmailAddress(final String emailAddress) {
    this.emailAddress = emailAddress;
    return this;
    }

    public Builder withTelephone(final String telephone) {
    this.telephone = telephone;
    return this;
    }

    public Builder withDateOfBirth(final Date dateOfBirth) {
    this.dateOfBirth = dateOfBirth;
    return this;
    }

    public Builder BuilderwithEmailAddress(final String emailAddress) {
    this.emailAddress = emailAddress;
    return this;
    }

    public Pet build() {
    if (animal == null || petName == null || ownerName == null ||
    address == null || telephone == null) {
    throw new IllegalStateException("Cannot create Pet");
    }

    return new Pet(animal, petName, ownerName, address,
    telephone, dateOfBirth, emailAddress);
    }
    }

    private final String animal;
    private final String petName;
    private final String ownerName;
    private final String address;
    private final String telephone;
    private final Date dateOfBirth;
    private final String emailAddress;

    public Pet(String animal, String petName, String ownerName, String address,
    String telephone, Date dateOfBirth, String emailAddress) {
    this.animal = animal;
    this.petName = petName;
    this.ownerName = ownerName;
    this.address = address;
    this.telephone = telephone;
    this.dateOfBirth = dateOfBirth;
    this.emailAddress = emailAddress;
    }


    }

    Builder 클래스는 Pet 클래스의 일부이며 Pet 객체를 생성하는 전적인 권한이 있다.

    생성자를 사용하면 어떤 매개변수를 사용할지를 매개변수의 순서가 결정했다.

    하지만 빌더패턴을 사용함으로써 각 값을 정확히 어떻게 사용하는지 이해가 쉽고, 순서에 상관없이 호출하고 싶은 데로 호출할 수도 있다.


    테스트 코드

    @Test
    public void legalBuild() {
    final Pet.Builder builder = new Pet.Builder();
    final Pet pet = builder
    .withAnimal("CAT")
    .withPetName("Squidge")
    .withOwnerName("Simon Smith")
    .withAddress("123 High Street")
    .withTelephone("07777777770")
    .withEmailAddress("test@email.com")
    .build();
    }

    @Test
    public void illegalBuild() {
    final Pet.Builder builder = new Pet.Builder();
    final Pet pet = builder
    .withAnimal("DOG")
    .withPetName("Fido")
    .withOwnerName("Simon Simith")
    .build();

    }


    'Java' 카테고리의 다른 글

    [Java] JDK, JRE  (0) 2021.02.27
    [Java] 자료구조  (0) 2016.11.04
    [Java] 이진탐색 Binary Search  (0) 2016.11.04
    [Java] 합병정렬 Merge Sort  (1) 2016.11.03
    [Java] 퀵 정렬 Quick Sort  (0) 2016.11.02
Designed by Tistory.