정의
복잡한 객체의 생성 과정과 표현 방법을 분리하여 동일한 생성 절차에서 서로 다른 표현 결과를 만들 수 있게 하는 패턴
생성자에 들어갈 모든 매개 변수를 받은 뒤에 이 변수들을 통합해서 한번에 객체를 생성하는 패턴
사용하는 이유
방법
public class PizzaStore {
private String name;
private String telNo;
private String location;
private String[] menus;
private String openTime;
private String closeTime;
public PizzaStore(String name){
this.name = name;
}
public PizzaStore(String name, String telNo){
this.name = name;
this.telNo = telNo;
}
public PizzaStore(String name, String telNo, String location){
this.name = name;
this.telNo = telNo;
this.location = location;
}
public PizzaStore(String name, String telNo, String location, String[] menus){
this.name = name;
this.telNo = telNo;
this.location = location;
this.menus = menus;
}
public PizzaStore(String name, String telNo, String location, String[] menus, String openTime, String closeTime){
this.name = name;
this.telNo = telNo;
this.location = location;
this.menus = menus;
this.openTime = openTime;
this.closeTime = closeTime;
}
}
public class PizzaStoreBuilder {
String name;
String telNo;
String location;
String[] menus;
String openTime;
String closeTime;
public PizzaStoreBuilder setName(String name) {
this.name = name;
return this;
}
public PizzaStoreBuilder setTelNo(String telNo) {
this.telNo = telNo;
return this;
}
public PizzaStoreBuilder setLocation(String location) {
this.location = location;
return this;
}
public PizzaStoreBuilder setMenus(String[] menus) {
this.menus = menus;
return this;
}
public PizzaStoreBuilder setOpenTime(String openTime) {
this.openTime = openTime;
return this;
}
public PizzaStoreBuilder setCloseTime(String closeTime) {
this.closeTime = closeTime;
return this;
}
public PizzaStore build() {
PizzaStore pizzaStore = new PizzaStore(name, telNo, location, menus, openTime, closeTime );
return pizzaStore;
}
@Override
public String toString() {
return "PizzaStore{" +
"name='" + name + '\'' +
", telNo='" + telNo + '\'' +
", location='" + location + '\'' +
", menus=" + Arrays.toString(menus) +
", openTime='" + openTime + '\'' +
", closeTime='" + closeTime + '\'' +
'}';
}
}
TEST CODE
public class BuilderTest {
public static void main(String[] args) {
PizzaStore pizzaStore1 = new PizzaStore(
"pizza school","01012341234","서울시 송파구",
new String[]{"cheese","pepperoni"},"09:00","21:00");
PizzaStore pizzaStore2 = new PizzaStoreBuilder()
.setName("pizza school")
.setTelNo("01012341234")
.setLocation("서울시 송파구")
.setMenus(new String[]{"cheese","pepperoni"})
.setOpenTime("09:00")
.setCloseTime("21:00")
.build();
PizzaStore pizzaStore3 = new PizzaStoreBuilder()
.setName("pizza school")
.setTelNo("01012341234")
.setLocation("서울시 송파구")
.setMenus(new String[]{"cheese","pepperoni"})
.build();
System.out.println(pizzaStore1);
System.out.println(pizzaStore2);
System.out.println(pizzaStore3);
}
}