Java에서 프로토타입 디자인 패턴

프로토타입 디자인 패턴은 생성 디자인 패턴 중 하나이며, 객체 생성의 메커니즘을 제공합니다.

프로토타입 디자인 패턴

객체 생성이 비용이 많이 들고 많은 시간과 자원이 필요한 경우, 이미 비슷한 객체가 있는 경우에 사용됩니다. 프로토타입 패턴은 원본 객체를 새 객체로 복사한 다음 우리의 필요에 따라 수정할 수 있는 메커니즘을 제공합니다. 프로토타입 디자인 패턴은 자바 클론을 사용하여 객체를 복사합니다.

프로토타입 디자인 패턴 예제

프로토타입 디자인 패턴을 예를 통해 이해하는 것이 쉽습니다. 데이터베이스에서 데이터를 로드하는 객체가 있다고 가정해 보겠습니다. 이제 프로그램에서 이 데이터를 여러 번 수정해야 하므로, new 키워드를 사용하여 객체를 만들고 다시 데이터베이스에서 모든 데이터를 로드하는 것은 좋은 아이디어가 아닙니다. 더 나은 접근 방법은 기존 객체를 새 객체로 복제한 다음 데이터 조작을 수행하는 것입니다. 프로토타입 디자인 패턴은 복사 중인 객체가 복사 기능을 제공해야 한다는 것을 요구합니다. 이는 다른 클래스에서 수행해서는 안 됩니다. 그러나 객체 속성의 얕은 복사 또는 깊은 복사를 사용할지는 요구 사항에 따라서이며, 이는 디자인 결정입니다. 다음은 자바에서 프로토타입 디자인 패턴 예제를 보여주는 샘플 프로그램입니다. Employees.java

package com.journaldev.design.prototype;

import java.util.ArrayList;
import java.util.List;

public class Employees implements Cloneable{

	private List empList;
	
	public Employees(){
		empList = new ArrayList();
	}
	
	public Employees(List list){
		this.empList=list;
	}
	public void loadData(){
		// 데이터베이스에서 모든 직원을 읽어와 리스트에 넣습니다.
		empList.add("Pankaj");
		empList.add("Raj");
		empList.add("David");
		empList.add("Lisa");
	}
	
	public List getEmpList() {
		return empList;
	}

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

주목해야 할 점은 직원 목록의 깊은 복사를 제공하기 위해 clone 메서드가 재정의되었다는 것입니다. 다음은 프로토타입 디자인 패턴 예제 테스트 프로그램입니다. 이것은 프로토타입 패턴의 이점을 보여줍니다. PrototypePatternTest.java

package com.journaldev.design.test;

import java.util.List;

import com.journaldev.design.prototype.Employees;

public class PrototypePatternTest {

	public static void main(String[] args) throws CloneNotSupportedException {
		Employees emps = new Employees();
		emps.loadData();
		
		// clone 메서드를 사용하여 직원 객체를 가져옵니다.
		Employees empsNew = (Employees) emps.clone();
		Employees empsNew1 = (Employees) emps.clone();
		List list = empsNew.getEmpList();
		list.add("John");
		List 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]

객체 복제 기능이 제공되지 않았다면, 매번 데이터베이스 호출을 수행하여 직원 목록을 가져와야 했을 것입니다. 그런 다음 시간이 많이 걸리고 자원이 소모되는 조작을 수행해야 했을 것입니다. 이것이 자바에서의 프로토타입 디자인 패턴에 대한 모든 내용입니다.

Source:
https://www.digitalocean.com/community/tutorials/prototype-design-pattern-in-java