프로토타입 패턴

2020-02-10

프로토타입 패턴

프로토타입 패턴은 객체 생성이 비용이 많이들거나 시간이 많이 걸리거나, 이미 비슷한 객체가 존재할 경우 사용됩니다.

프로토타입 패턴은 원래의 객체를 새로운 객체로 복사한 후 필요에 따라 수정하는 메카니즘을 갖고 있습니다.

프로토타입 패턴 예제

데이터베이스로부터 데이터를 불러오는 객체가 있다고 가정해봅시다. 이 받아온 데이터를 여러 번에 걸쳐서 수정할 건데, new 연산자를 이용해서 객체를 만들거나 다시 데이터베이스에서 모든 데이터를 가져오는 건 그리 좋은 방법은 아닙니다.

더 좋은 방법은 이미 만들어진 객체를 새로운 객체로 복사 한후 데이터를 변경하는 방법입니다.

프로토타입 패턴은 복사하려는 객체가 복사 기능을 제공해야 합니다. 결코 다른 클래스에 의해서 복사가 이루어지면 안됩니다. 얕은 복사(Shallow copy)든 깊은 복사(deep copy)든 두개를 아무거나 사용할 수 있는데, 요구 사항과 디자인 패턴의 결정에 따라 달라집니다.

Employees.java

public class Employees implements Cloneable{

	private List<String> empList;
	
	public Employees(){
		empList = new ArrayList<String>();
	}
	
	public Employees(List<String> list){
		this.empList=list;
	}
	public void loadData(){
		//모든 데이터를 불러오는 작업
		empList.add("Pankaj");
		empList.add("Raj");
		empList.add("David");
		empList.add("Lisa");
	}
	
	public List<String> getEmpList() {
		return empList;
	}

	@Override
	public Object clone() throws CloneNotSupportedException{
			List<String> temp = new ArrayList<String>();
			for(String s : this.getEmpList()){
				temp.add(s);
			}
			return new Employees(temp);
	}
	
}

empList를 깊은 복사를 해주기 위해서 clone 메소드를 오버라이드 했습니다.

테스트

PrototypePatternTest.java

public class PrototypePatternTest {

	public static void main(String[] args) throws CloneNotSupportedException {
		Employees emps = new Employees();
		emps.loadData();
		
    //깊은 복사 이용
		Employees empsNew = (Employees) emps.clone();
		Employees empsNew1 = (Employees) emps.clone();
		List<String> list = empsNew.getEmpList();
		list.add("John");
		List<String> list1 = empsNew1.getEmpList();
		list1.remove("Pankaj");
		
		System.out.println("emps List: "+emps.getEmpList());
		System.out.println("empsNew List: "+list);
		System.out.println("empsNew1 List: "+list1);
	}

}

결과

emps List: [Pankaj, Raj, David, Lisa]
empsNew List: [Pankaj, Raj, David, Lisa, John]
empsNew1 List: [Raj, David, Lisa]

객체 복사를 제공해주지 않으면, employee 리스트들을 매번 데이터베이스에서 불러와야합니다.