티스토리 뷰

Programming/디자인 패턴

Builder Pattern

Albothyl 2019. 1. 24. 13:42

Builder Pattern

복합 객체의 생성 과정과 표현 방법을 분리하여 동일한 생성 절차에서 서로 다른 표현 결과를 만들 수 있게 하는 패턴이다.

- 별도의 Builder는 자신을 리턴하여 stream 형태로 데이터를 입력받을 수 있다.

- Builder를 생성자로 입력받아 Builder에 입력된 파라미터로 인스턴스를 생성한다.






public final class Hero {

  private final String profession;

  private final String name;

  private final String hairType;

  private final String hairColor;

  private final String armor;

  private final String weapon;


  private Hero(Builder builder) {

    this.profession = builder.profession;

    this.name = builder.name;

    this.hairColor = builder.hairColor;

    this.hairType = builder.hairType;

    this.weapon = builder.weapon;

    this.armor = builder.armor;

  }



  public static class Builder {

    private final String profession;

    private final String name;

    private String hairType;

    private String hairColor;

    private String armor;

    private String weapon;


    public Builder(String profession, String name) {

      if (profession == null || name == null) {

        throw new IllegalArgumentException("profession and name can not be null");

      }

      this.profession = profession;

      this.name = name;

    }


    public Builder withHairType(String hairType) {

      this.hairType = hairType;

      return this;

    }


    public Builder withHairColor(String hairColor) {

      this.hairColor = hairColor;

      return this;

    }


    public Builder withArmor(String armor) {

      this.armor = armor;

      return this;

    }


    public Builder withWeapon(String weapon) {

      this.weapon = weapon;

      return this;

    }


    public Hero build() {

      return new Hero(this);

    }

  }

}



public class App {

  public static void main(String[] args) {

    Hero mage = new Hero.Builder("MAGE", "Riobard")

        .withHairColor("BLACK")

        .withWeapon("DAGGER")

                        .build();

    System.out.println(mage.toString());


    Hero warrior = new Hero.Builder("WARRIOR", "Amberjill")

                          .withHairColor("BLOND")

                          .withHairType("LONG_CURLY")

                          .withArmor("CHAIN_MAIL")

                          .withWeapon("SWORD")

                          .build();

    System.out.println(warrior.toString());


    Hero thief = new Hero.Builder("THIEF", "Desmond")

                      .withHairType("BALD")

                      .withWeapon("BOW")

                      .build();

    System.out.println(thief.toString());

  }

}


'Programming > 디자인 패턴' 카테고리의 다른 글

Observer Pattern  (0) 2019.01.24
Factory Method Pattern  (0) 2019.01.24
Template Method Pattern  (0) 2019.01.24
Strategy Pattern  (0) 2019.01.24
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
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 27 28 29 30 31
글 보관함