class Hamburger {
// 필수 매개변수
private int bun;
private int patty;
// 선택 매개변수
private int cheese;
private int lettuce;
private int tomato;
private int bacon;
public Hamburger(int bun, int patty, int cheese, int lettuce, int tomato, int bacon) {
this.bun = bun;
this.patty = patty;
this.cheese = cheese;
this.lettuce = lettuce;
this.tomato = tomato;
this.bacon = bacon;
}
public Hamburger(int bun, int patty, int cheese, int lettuce, int tomato) {
this.bun = bun;
this.patty = patty;
this.cheese = cheese;
this.lettuce = lettuce;
this.tomato = tomato;
}
public Hamburger(int bun, int patty, int cheese, int lettuce) {
this.bun = bun;
this.patty = patty;
this.cheese = cheese;
this.lettuce = lettuce;
}
public Hamburger(int bun, int patty, int cheese) {
this.bun = bun;
this.patty = patty;
this.cheese = cheese;
}
...
}
public static void main(String[] args) {
// 모든 재료가 있는 햄버거
Hamburger hamburger1 = new Hamburger(2, 1, 2, 4, 6, 8);
// 빵과 패티 치즈만 있는 햄버거
Hamburger hamburger2 = new Hamburger(2, 1, 1);
// 빵과 패티 베이컨만 있는 햄버거
Hamburger hamburger3 = new Hamburger(2, 0, 0, 0, 0, 6);
}
setter() 를 외부에서 사용 가능하기 때문에 내용이 변경될 여지가 존재한다. class Hamburger {
// 필수 매개변수
private int bun;
private int patty;
// 선택 매개변수
private int cheese;
private int lettuce;
private int tomato;
private int bacon;
public Hamburger() {}
public void setBun(int bun) {
this.bun = bun;
}
public void setPatty(int patty) {
this.patty = patty;
}
public void setCheese(int cheese) {
this.cheese = cheese;
}
public void setLettuce(int lettuce) {
this.lettuce = lettuce;
}
public void setTomato(int tomato) {
this.tomato = tomato;
}
public void setBacon(int bacon) {
this.bacon = bacon;
}
}
public static void main(String[] args) {
// 모든 재료가 있는 햄버거
Hamburger hamburger1 = new Hamburger();
hamburger1.setBun(2);
hamburger1.setPatty(1);
hamburger1.setCheese(2);
hamburger1.setLettuce(4);
hamburger1.setTomato(6);
hamburger1.setBacon(8);
// 빵과 패티 치즈만 있는 햄버거
Hamburger hamburger2 = new Hamburger();
hamburger2.setBun(2);
hamburger2.setPatty(1);
hamburger2.setCheese(2);
// 빵과 패티 베이컨만 있는 햄버거
Hamburger hamburger3 = new Hamburger();
hamburger3.setBun(2);
hamburger2.setPatty(1);
hamburger3.setBacon(8);
}
build() 메소드로 하나의 인스턴스를 생성하여 리턴하는 패턴🍔 수제 햄버거를 주문할때 빵이나 패티 등 속재료들은 주문하는 사람의 취향에 따라 치즈를 뺄 수도 , 토마토를 뺄 수도 있다. 이처럼 선택적인 속재료들을 보다 유연하게 받아 다양한 타입의 인스턴스를 생성할 수 있어 , 클래스의 선택적 매개변수가 많은 상황에서 유용하게 사용된다.
public static void main(String[] args) {
// 생성자 방식
Hamburger hamburger = new Hamburger(2, 3, 0, 3, 0, 0);
// 빌더 방식
Hamburger hamburger = new Hamburger.Builder(10)
.bun(2)
.patty(3)
.lettuce(3)
.build();
}
출처
빌더(Builder) 패턴 - 완벽 마스터하기 https://inpa.tistory.com/entry/GOF-%F0%9F%92%A0-%EB%B9%8C%EB%8D%94Builder-%ED%8C%A8%ED%84%B4-%EB%81%9D%ED%8C%90%EC%99%95-%EC%A0%95%EB%A6%AC
[디자인 패턴] 점층적 생성자 패턴 (Telescoping Constructor Pattern)
JavaBeans Pattern이 뭐야 https://velog.io/@dhwlddjgmanf/JavaBeans-Pattern%EC%9D%B4-%EB%AD%90%EC%95%BC-lq9cyh9a