Javaにおけるプロトタイプデザインパターン。

プロトタイプデザインパターンは、オブジェクトの生成メカニズムを提供するためのCreational Designパターンの一つです。

プロトタイプデザインパターン

プロトタイプデザインパターンは、オブジェクトの作成が高コストで時間とリソースを多く要する場合や、既に類似したオブジェクトが存在している場合に使用されます。プロトタイプパターンは、元のオブジェクトを新しいオブジェクトにコピーし、必要に応じて修正するメカニズムを提供します。プロトタイプデザインパターンでは、Javaのクローニングを使用してオブジェクトをコピーします。

プロトタイプデザインパターンの例

例を用いれば、プロトタイプデザインパターンは簡単に理解できるでしょう。データベースからデータを読み込むオブジェクトがあるとしましょう。このデータをプログラム内で複数回変更する必要がある場合、newキーワードを使用してオブジェクトを作成し、データベースから再度すべてのデータを読み込むのは良い考えではありません。より良いアプローチは、既存のオブジェクトをクローンして新しいオブジェクトを作成し、その後データ操作を行うことです。プロトタイプデザインパターンでは、コピーするオブジェクトはコピー機能を提供する必要があります。他のクラスでは行うべきではありません。ただし、オブジェクトのプロパティの浅いコピーまたは深いコピーを使用するかは、要件に応じて設計上の決定です。以下に、Javaでのプロトタイプデザインパターンの例を示すプログラムがあります。Employees.java

package com.scdev.design.prototype;

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

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(){
		//read all employees from database and put into the list
		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);
	}
	
}

従業員リストの深いコピーを提供するために、cloneメソッドがオーバーライドされていることに注意してください。プロトタイプデザインパターンの利点を示すための例として、PrototypePatternTest.javaというテストプログラムがあります。

package com.scdev.design.test;

import java.util.List;

import com.scdev.design.prototype.Employees;

public class PrototypePatternTest {

	public static void main(String[] args) throws CloneNotSupportedException {
		Employees emps = new Employees();
		emps.loadData();
		
		//Use the clone method to get the Employee object
		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]

オブジェクトのクローニングが提供されていない場合、従業員リストを取得するためにデータベース呼び出しを行わなければなりません。そして、リソースと時間を消費する操作を行わなければなりません。これがJavaにおけるプロトタイプデザインパターンの全てです。

コメントを残す 0

Your email address will not be published. Required fields are marked *