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);
}
}
}