Java 中的原型设计模式

原型设计模式是创意设计模式之一,因此它提供了对象创建的机制。

原型设计模式

prototype design pattern Prototype design pattern is used when the Object creation is a costly affair and requires a lot of time and resources and you have a similar object already existing. Prototype pattern provides a mechanism to copy the original object to a new object and then modify it according to our needs. Prototype design pattern uses java cloning to copy the object.

原型设计模式示例

假设我们有一个从数据库上加载数据的对象,现在我们需要在我们的程序中多次修改这些数据,所以使用关键字创建对象并从数据库中重新加载所有数据并不是一个好主意。更好的方法是将现有对象克隆成一个新的对象,然后进行数据操纵。原型设计模式命令你正在复制的对象应该提供复制功能。这不应该由任何其他类进行。然而,使用浅层或深层副本的对象属性取决于要求和设计决定。

 1package com.journaldev.design.prototype;
 2
 3import java.util.ArrayList;
 4import java.util.List;
 5
 6public class Employees implements Cloneable{
 7
 8    private List<String> empList;
 9    
10    public Employees(){
11    	empList = new ArrayList<String>();
12    }
13    
14    public Employees(List<String> list){
15    	this.empList=list;
16    }
17    public void loadData(){
18    	//read all employees from database and put into the list
19    	empList.add("Pankaj");
20    	empList.add("Raj");
21    	empList.add("David");
22    	empList.add("Lisa");
23    }
24    
25    public List<String> getEmpList() {
26    	return empList;
27    }
28
29    @Override
30    public Object clone() throws CloneNotSupportedException{
31    		List<String> temp = new ArrayList<String>();
32    		for(String s : this.getEmpList()){
33    			temp.add(s);
34    		}
35    		return new Employees(temp);
36    }
37    
38}

请注意,克隆方法被覆盖以提供员工列表的深度副本. 这里是原型设计模式示例测试程序,将显示原型模式的好处。

 1package com.journaldev.design.test;
 2
 3import java.util.List;
 4
 5import com.journaldev.design.prototype.Employees;
 6
 7public class PrototypePatternTest {
 8
 9    public static void main(String[] args) throws CloneNotSupportedException {
10    	Employees emps = new Employees();
11    	emps.loadData();
12    	
13    	//Use the clone method to get the Employee object
14    	Employees empsNew = (Employees) emps.clone();
15    	Employees empsNew1 = (Employees) emps.clone();
16    	List<String> list = empsNew.getEmpList();
17    	list.add("John");
18    	List<String> list1 = empsNew1.getEmpList();
19    	list1.remove("Pankaj");
20    	
21    	System.out.println("emps List: "+emps.getEmpList());
22    	System.out.println("empsNew List: "+list);
23    	System.out.println("empsNew1 List: "+list1);
24    }
25
26}

上述原型设计模式示例程序的输出是:

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

如果对象克隆没有提供,我们将不得不进行数据库调用,以便每次检索员工列表,然后进行资源和时间耗费的操作,这就是Java中的原型设计模式。

Published At
Categories with 技术
comments powered by Disqus