一 定义
使用原型实例指定待创建对象的类型,并且通过复制这个原型来创建新的对象。其实就是浅拷贝和深拷贝
二 代码实现
public class Person implements Cloneable { private String name; private String age; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age='" + age + '\'' + '}'; } @Override public Person clone(){ try { return (Person) super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); return null; } } }
public class Teacher implements Cloneable { private String name; private Person person; public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Teacher{" + "name='" + name + '\'' + ", person=" + person + '}'; } @Override public Teacher clone(){ try { Teacher teacher = (Teacher) super.clone(); Person person = teacher.getPerson(); teacher.setPerson(person.clone()); return teacher; } catch (CloneNotSupportedException e) { e.printStackTrace(); return null; } } }
测试
public class PrototypeTest { public static void main( String[] args ) { Teacher teacher = new Teacher(); teacher.setName("wang"); Person person = new Person(); person.setName("li"); person.setAge("30"); teacher.setPerson(person); System.out.println(teacher.toString()); Teacher teacher1 = teacher.clone(); teacher.setName("zhang"); person.setName("zhangzhang"); System.out.println(teacher.toString()); System.out.println(teacher1.toString()); } }
输出
Connected to the target VM, address: '127.0.0.1:55142', transport: 'socket' Disconnected from the target VM, address: '127.0.0.1:55142', transport: 'socket' Teacher{name='wang', person=Person{name='li', age='30'}} Teacher{name='zhang', person=Person{name='zhangzhang', age='30'}} Teacher{name='wang', person=Person{name='li', age='30'}} Process finished with exit code 0
一只小飞机