Prototype Pattern
Prototype Pattern được sử dụng khi việc khởi tạo đối tượng của lớp là một công việc tốn kém đòi hỏi nhiều thời gian và tài nguyên đồng thời bạn có một đối tượng tương tự như vậy đang tồn tại. Prototype Pattern cung cấp cơ chế để sao chép đối tượng gốc tới đối tượng mới đang được tạo và rồi chỉnh sửa nó theo yêu cầu mới. Pattern này sử dụng cơ chế cloning của Java để sao chép đối tượng.
Có thể hiểu được Prototype pattern dễ dàng hơn thông qua ví dụ. Giả sử chúng ta có 1 đối tượng dùng để tải dữ liệu từ cơ sở dữ liệu. Và chúng ta cần chỉnh sửa dữ liệu này nhiều lần trong chương trình của mình. Vì vậy, sử dụng từ khóa new để khởi tạo đối tượng và tải lại dữ liệu từ cơ sở dữ liệu không phải là một ý hay.
Một cách tiếp cận tốt hơn là sao chép đối tượng hiện có vào đối tượng mới được tạo và sau đó thực hiện các thao tác trên dữ liệu.
Ví dụ sau đây mô tả cách thức hoạt động của Prototype Pattern.
Employees.java
package com.journaldev.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); } }
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(); //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); } }
Kết quả chạy chương trình như sau:
emps HashMap: [Pankaj, Raj, David, Lisa] empsNew HashMap: [Pankaj, Raj, David, Lisa, John] empsNew1 HashMap: [Raj, David, Lisa]
No comments :
Post a Comment