💡 객체를 생성하는 데 비용이 많이 들고, 비슷한 객체가 이미 있는 경우에 사용되는 생성 패턴 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 커넥션 없이 복사해서 수정해서 사용
}
}