原型模式用于创建重复对象,在JAVA中可以通过继承Cloneable接口,该接口仅作为一个标记,并没有提供具体方法,然后通过覆盖Object的clone()方法,该方法是native的,由虚拟机帮我们实现对象的克隆。
其中,当一个对象中的成员为immutable的时(int、short、long、String等基本数据类型及其包装类),使用浅拷贝。当对象中的成员包含mutable成员时(例如另外一个对象),则需要让另外一个对象也实现Cloneable接口,这种方式属于深拷贝。
package com.depthmind.designpattern;
public class PrototypePattern {
public static void main(String[] args) throws CloneNotSupportedException {
Employee employee = new Employee();
employee.setName("depthmind");
employee.setPosition("manager");
Company company = new Company("depthmind", "Beijing");
employee.setCompany(company);
Employee employee1 = employee.clone();
System.out.println(employee);
System.out.println(employee1);
company.setAddress("Shanghai");
employee.setCompany(company);
System.out.println(employee);
System.out.println(employee1);
}
}
class Company implements Cloneable{
private String name;
private String address;
public Company(String name, String address) {
this.name = name;
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Company{" +
"name='" + name + '\'' +
", address='" + address + '\'' +
'}' + "....hashcode=" + this.hashCode();
}
@Override
protected Company clone() throws CloneNotSupportedException {
return (Company) super.clone();
}
}
class Employee implements Cloneable{
private String name;
private String position;
private Company company;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public Company getCompany() {
return company;
}
public void setCompany(Company company) throws CloneNotSupportedException {
this.company = company;
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", position='" + position + '\'' +
", company=" + company +
'}' + "....hashcode=" + this.hashCode();
}
@Override
protected Employee clone() throws CloneNotSupportedException {
Employee employee = (Employee) super.clone();
Company company1 = company.clone();
employee.setCompany(company1);
return employee;
}
}