💡 객체를 생성하는 데 비용이 많이 들고, 비슷한 객체가 이미 있는 경우에 사용되는 생성 패턴 Original 객체를 새로운 객체에 복사하여 필요에 따라 수정하는 매커니즘을 제공
구조와 기본 개념
- PrototypeRegistry는 interface인 Prototype 에만 의존
- 외부로 부터 주입된 Button 클래스의 clone()을 사용하여 Button 클래스를 생성
- 프로토타입 패턴은 객체를 생성하는데 시간과 노력이 많이 들고, 이미 유사한 객체가 존재하는 경우 사용
- java의 clone()을 이용하기 때문에 생성하고자 하는 객체의 clone() 메소드를 오버라이드 해야 함
- Java의 기본적인 clone()은 얕은 복사이므로!
예시
- Student List를 DB에서 항상 같은 결과로 가져오는 프로그램이 있다고 가정
public class Teacher implements Cloneable {
private List<Student> students;
public Teacher() {
this.students = new ArrayList<>();
}
public Teacher(List<Student> students) {
this.students = students;
}
public List<Student> getStudents() {
return students;
}
public void listAll() {
// db에서 학생 정보들을 가져오는 메소드
this.students.add(new Student("kim",1));
this.students.add(new Student("lee",2));
this.students.add(new Student("park",3));
}
@Override
protected Object clone() throws CloneNotSupportedException {
return new Teacher(new ArrayList<>(this.students));
}
}
- 매번 DB에 연결해서 학생들 정보를 가져오는 것은 비용이 큼 (여기서는 listAll() 메소드)
public class Classroom {
private Cloneable cloneable;
public Classroom(CLoneable cloneable) {
this.cloneable = cloneable;
}
public Cloneable makeTeacher() {
cloneable.listAll(); // DB에서 학생 정보들 가져옴
return cloneable.clone();
}
}
public class Main {
public static void main(String[] args) {
Classroom class = new Classroom(new Teacher());
Teacher teacher1 = class.makeTeacher(); // makeTeacher 내의 listAll로 가져옴
Teacher teacher2 = teacher1.clone(); // listAll 없이 teacher clone
List<Student> teacher1Students = teacher1.getStudents();
List<Student> teacher2Students = teacher2.getStudents();
teacher2Students.add("kang"); // 새로 DB 커넥션 없이 복사해서 수정해서 사용
}
}
- 위와 같이 비용이 큰 DB 커넥션 대신에 이미 가져온 결과를 수정하여 사용하면 효율적임
장점 & 단점
- 장점
- 구현 클래스에 직접 연결하지 않고 객체를 복사할 수 있음
- 프로토타입이 미리 정의되어 있기 때문에 중복되는 초기화 코드를 제거
- 복잡한 오브젝트를 보다 편리하게 만들수 있음
- 단점
- 순환참조가 있는 복잡한 객체를 복제하는 것은 까다로움
Reference
'개인 공부' 카테고리의 다른 글
정적 팩토리 메서드 (0) | 2022.11.21 |
---|---|
Logback.xml 동일 패키지 내 다른 레벨 처리 (2) | 2022.11.10 |
Garbage Collector 동작원리 (0) | 2022.11.01 |
도커(Docker)와 가상머신(VM) (0) | 2022.10.28 |
String, StringBuilder, StringBuffer 사용 경우 (0) | 2022.10.28 |