1. 개요
- 프로토타입 디자인 패턴 (Prototype Design Pattern)은 기존 객체를 복제하여 새로운 객체를 생성하는 패턴이다.
2. 상황
- 객체 생성에 필요한 리소스나 시간이 많이 소요될 때
3. 다이어그램
3.1. 설명
Prototype
- 복제를 지원하는 인터페이스 또는 추상 클래스이다.
- 복제 메소드를 정의하고, 자기 자신을 복제하여 새로운 객체를 생성한다.
ConcretePrototype
Prototype
구현한 실제 객체이다.- 자기 자신을 복제하여 새로운 객체를 생성하는 기능을 구현한다.
4. 구현
public interface Prototype { Prototype clone(); }
public class ConcretePrototype implements Prototype {
private int id;
public ConcretePrototype(int id) { this.id = id; }
@Override
public Prototype clone() { return new ConcretePrototype(id); }
public int getId() { return id; }
}
public class Client {
public static void main(String[] args) {
ConcretePrototype original = new ConcretePrototype(1);
ConcretePrototype cloned = (ConcretePrototype) original.clone();
System.out.println("Original ID: " + original.getId());
System.out.println("Cloned ID: " + cloned.getId());
}
}
출력결과
Original ID: 1
Cloned ID: 1
5. 예시
public interface ProductPrototype {
ProductPrototype clone();
void setPrice(double price);
void getInfo();
}
public class ConcreteProduct implements ProductPrototype {
private String name;
private double price;
public ConcreteProduct(String name, double price) {
this.name = name;
this.price = price;
}
@Override
public ProductPrototype clone() {
return new ConcreteProduct(this.name, this.price);
}
@Override
public void setPrice(double price) { this.price = price; }
@Override
public void getInfo() {
System.out.println("Product: " + name + ", Price: " + price);
}
}
public class Client {
public static void main(String[] args) {
ConcreteProduct original = new ConcreteProduct("Original", 100.0);
original.getInfo();
ConcreteProduct cloned = (ConcreteProduct) original.clone();
cloned.setPrice(150.0);
cloned.getInfo();
}
}
출력결과
Product: Original, Price: 100.0
Product: Original, Price: 150.0
6. 장단점
6.1. 장점
- 객체 생성 과정을 추상화하여 유연성과 확장성을 제공한다.
- 객체의 종류를 동적으로 결정할 수 있다.
- OCP를 만족한다.
6.2. 단점
- 코드의 복잡성이 증가한다.
- 객체의 깊은 복사가 어려울 수 있다.
관련 포스팅
728x90
'Develop > Design Pattern' 카테고리의 다른 글
[Design Pattern] 팩토리 (Factory) 패턴 (0) | 2023.12.20 |
---|---|
[Design Pattern] 단순 팩토리 (Simple Factory) 패턴 (0) | 2023.12.18 |
[Design Pattern] 옵저버 (Observer) 패턴 (0) | 2023.11.14 |
[Design Pattern] 메멘토 (Memento) 패턴 (0) | 2023.11.13 |
[Design Pattern] 명령 (Command) 패턴 (0) | 2023.11.06 |