. 이번 글에서는 빌더 패턴(Builder Pattern)과 프로토타입 패턴(Prototype Pattern)에 대해 알아보고, 각각의 실제 활용 사례, 장단점, 그리고 유의점을 살펴보겠습니다.
StringBuilder는 문자열을 동적으로 생성할 때 사용됩니다.java
class Product {
private String partA;
private String partB;
private String partC;
public static class Builder {
private String partA;
private String partB;
private String partC;
public Builder setPartA(String partA) {
this.partA = partA;
return this;
}
public Builder setPartB(String partB) {
this.partB = partB;
return this;
}
public Builder setPartC(String partC) {
this.partC = partC;
return this;
}
public Product build() {
Product product = new Product();
product.partA = this.partA;
product.partB = this.partB;
product.partC = this.partC;
return product;
}
}
@Override
public String toString() {
return "Product [partA=" + partA + ", partB=" + partB + ", partC=" + partC + "]";
}
}
// 사용
Product product = new Product.Builder()
.setPartA("Engine")
.setPartB("Wheels")
.setPartC("Chassis")
.build();
System.out.println(product);
prototype을 사용하면, 매번 새 객체를 생성합니다.java
class Prototype implements Cloneable {
private String field;
public Prototype(String field) {
this.field = field;
}
public void setField(String field) {
this.field = field;
}
public String getField() {
return field;
}
@Override
protected Prototype clone() throws CloneNotSupportedException {
return (Prototype) super.clone();
}
@Override
public String toString() {
return "Prototype [field=" + field + "]";
}
}
// 사용
Prototype original = new Prototype("Original");
try {
Prototype clone = original.clone();
clone.setField("Clone");
System.out.println(original); // Prototype [field=Original]
System.out.println(clone); // Prototype [field=Clone]
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
Cloneable 인터페이스 사용이 권장되지 않는 경우도 있다.| 특징 | 빌더 패턴 | 프로토타입 패턴 |
|---|---|---|
| 목적 | 복잡한 객체 생성 | 객체의 복제 |
| 유연성 | 생성 과정의 유연성 제공 | 런타임 시점의 상태 복제 |
| 적용 시점 | 생성 단계가 복잡한 경우 사용 | 객체 생성 비용이 높은 경우 사용 |
| 코드 작성 방식 | 빌더 클래스를 작성 | 클론 메서드 구현 |
두 패턴 모두 특정 문제에 적합한 솔루션을 제공하며, 상황에 맞게 선택하는 것이 중요합니다. 🚀