
정의
실제 DB와 연동되는 예제 코드를 작성하는 것은 복잡할 수 있으므로, 직원의 명단을 갖고있는 Employees 클래스를 통해 살펴보겠습니다.
public class Employees implements Cloneable {
	
    private List<String> empList;
    
    public Employees() {
    	empList = new ArrayList<String>();
    }
    
    public void loadData() {
    	// 실제 DB와 연동되는 코드는 복잡하니 list에 직접 데이터를 넣어주겠습니다.
        empList.add("Pankaj");
        empList.add("Raj");
        empList.add("David");
        empList.add("Lisa");
    }
    
    public List<String> getEmpList() {
    	return empList;
    }
    
    // clone() 메소드를 정의하여 해당 객체를 복사하여 반환해줍니다.
    @Override
    public Object clone() throws CloneNotSupportedException {
    	List<String> temp = new ArrayList<String>();
        for(String s : this.empList) {
        	temp.add(s);
        }
        return new Employees(temp);
    }
}작성한 코드를 테스트해보겠습니다.
public class PrototypePatternTest {
	
    public static void main(String[] args) throws CloneNotSupportedException {
    	Employees emps = new Employees();
        emps.loadData(); // 최초에는 DB에 연결하여 데이터를 불러옵니다.
        
        // 이후에는 clone() 메소드를 사용하여 최초에 불러온 객체를 복사하여 필요에 맞게사용합니다.
		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]만약 Employees 클래스에서 clone()을 제공하지 않았다면, DB로부터 매번 employee 리스트를 직접 가져와야 했을 것이고, 그로 인해 상당히 큰 비용이 발생했을 것입니다.
하지만 프로토타입을 사용한다면 1회의 DB 접근을 통해 가져온 데이터를 복사하여 사용한다면 이를 해결할 수 있습니다. (객체를 복사하는 것이 네트워크 접근이나 DB 접근보다 훨씬 비용이 적습니다.)