Builder Pattern - dnwls16071/Backend_Summary GitHub Wiki

πŸ“š Builder Pattern μ„€λͺ…

  • λ³΅μž‘ν•œ 객체 생성 κ³Όμ •κ³Ό ν‘œν˜„ 방법을 λΆ„λ¦¬ν•˜μ—¬ λ‹€μ–‘ν•œ κ΅¬μ„±μ˜ μΈμŠ€ν„΄μŠ€λ₯Ό λ§Œλ“œλŠ” 생성 νŒ¨ν„΄μ΄λ‹€.
  • μŠ€ν”„λ§μ—μ„œλŠ” @Builder μ–΄λ…Έν…Œμ΄μ…˜ μ‚¬μš©μ΄ κ°€λŠ₯ν•˜λ‹€.

[Ex1]

/ Product class
class Pizza {
    private String dough;
    private String sauce;
    private String topping;

    // Private constructor to enforce the use of Builder
    private Pizza(PizzaBuilder builder) {
        this.dough = builder.dough;
        this.sauce = builder.sauce;
        this.topping = builder.topping;
    }

    @Override
    public String toString() {
        return "Pizza with " + dough + " dough, "
         + sauce + " sauce, and " + topping + " topping.";
    }

    public static class PizzaBuilder {
        private String dough;
        private String sauce;
        private String topping;

        // λ©”μ„œλ“œ 체이닝 κ°€λŠ₯(자기 μžμ‹ μ„ λ°˜ν™˜ν•˜λ―€λ‘œ)
        public PizzaBuilder dough(String dough) {
            this.dough = dough;
            return this;
        }

        // λ©”μ„œλ“œ 체이닝 κ°€λŠ₯(자기 μžμ‹ μ„ λ°˜ν™˜ν•˜λ―€λ‘œ)
        public PizzaBuilder sauce(String sauce) {
            this.sauce = sauce;
            return this;
        }
        
        // λ©”μ„œλ“œ 체이닝 κ°€λŠ₯(자기 μžμ‹ μ„ λ°˜ν™˜ν•˜λ―€λ‘œ)
        public PizzaBuilder topping(String topping) {
            this.topping = topping;
            return this;
        }

        public Pizza build() {
            return new Pizza(this);
        }
    }
}