IT_Fundamental/디자인 패턴
Builder Pattern(빌더패턴)
surhommejk
2017. 12. 11. 18:19
Builder Pattern(빌더패턴)
복잡한 것을 만들 때는 전체를 한꺼번에 만들기보다는 작게 분리하여 만든 후 다시 합치는 것이 편리하다. builder 패턴은 복잡한 인스턴스를 조립하여 만드는 구조로, 복합 객체를 생성할 때 객체를 생성하는 방법(과정)과 객체를 구현(표현)하는 방법을 분리한다. 따라서 이 패턴은 동일한 생성 절차에서 서로 다른 표현 결과를 만들 수 있다.
Robot
package BuilderPattern;
public class Robot {
String Head;
String Body;
String Leg;
public Robot(String head, String body, String leg) {
Head = head;
Body = body;
Leg = leg;
}
public String getHead() {
return Head;
}
public void setHead(String head) {
Head = head;
}
public String getBody() {
return Body;
}
public void setBody(String body) {
Body = body;
}
public String getLeg() {
return Leg;
}
public void setLeg(String leg) {
Leg = leg;
}
public void printRobotInfomation() {
System.out.println("머리 : " + Head);
System.out.println("몸통 : " + Body);
System.out.println("다리 : " + Leg);
}
}
Blueprint
package BuilderPattern;
public abstract class Blueprint {
public abstract void MakeHead();
public abstract void MakeBody();
public abstract void MakeLeg();
public abstract Robot getRobot();
}
KoreaRobotBlueprint
package BuilderPattern;
public class KoreaRobotBlueprint extends Blueprint {
private Robot robot;
public KoreaRobotBlueprint() {
robot = new Robot("defalt", "defalt", "defalt");
}
@Override
public void MakeHead() {
robot.setHead("태권 로봇머리");
}
@Override
public void MakeBody() {
robot.setBody("태권 로봇몸통");
}
@Override
public void MakeLeg() {
robot.setLeg("태권 로봇다리");
}
@Override
public Robot getRobot() {
return robot;
}
}
RobotFactory
package BuilderPattern;
public class RobotFactory {
private Blueprint bp;
public void setBlueprint(Blueprint bp) {
this.bp = bp;
}
public void MakeRobot() {
bp.MakeHead();
bp.MakeBody();
bp.MakeLeg();
}
public void getRobotInformation() {
bp.getRobot().printRobotInfomation();
}
}
Main
package BuilderPattern;
public class Main {
public static void main(String[] args) {
RobotFactory RF = new RobotFactory();
RF.setBlueprint(new KoreaRobotBlueprint());
// 여기서 오류나서 30분은 썼다.
// 기본적으로 무엇을 선언하고 초기화 하는 그 과정에서
// 메모리 할당 등 정확한 개념에 대해 숙지하지 못했기에
// 발생한 문제였다. 여기서 파라미터를 new KoreaRobotBlueprint()만 쓰는 건
// 여기서 생성자를 사용하는 것인데 문제는 내가 기본 생성자를 만들어 두지도 않고
// 사용했다는 것이다. 신기한건 이클립스에서 오류를 잡아주지 못했다는 건데
// 명심해두도록 한다.
RF.MakeRobot();
RF.getRobotInformation();
}
}