应用场景一个类需要创建多个实例
public class Teacher { public String educationtime = null; public String subject = null; }
public class School implements Cloneable { private String name =null; private String address = null; private ArrayList<String> style = new ArrayList<>(); private Teacher teacher = null; public School(String name){ this.name = name; teacher = new Teacher(); } public void setSummary(String address, ArrayList<String> style){ this.address = address; this.style = style; } public void setTeacher(String educationtime,String subject){ teacher.educationtime = educationtime; teacher.subject = subject; } public School clone() throws CloneNotSupportedException{ return (School)super.clone(); } public void display(){ System.out.println(this.name + " " + this.address); for(String st: style){ System.out.println("学校风格:" + st); } System.out.println("老师信息:" + teacher.educationtime + " " + teacher.subject); } }
public class School2 implements Cloneable { private String name =null; private String address = null; private ArrayList<String> style = new ArrayList<>(); private Teacher teacher = null; public School2(String name){ this.name = name; teacher = new Teacher(); } public void setSummary(String address, ArrayList<String> style){ this.address = address; this.style = style; } public void setTeacher(String educationtime,String subject){ teacher.educationtime = educationtime; teacher.subject = subject; } public School2 clone(){ String name = this.name; String address = this.address; ArrayList<String> style = new ArrayList<>(this.style); School2 copy = new School2(this.name); copy.setSummary(address,style); copy.setTeacher(this.teacher.educationtime,this.teacher.subject); return copy; } public void display(){ System.out.println(this.name + " " + this.address); for(String st: style){ System.out.println("学校风格:" + st); } System.out.println("老师信息:" + teacher.educationtime + " " + teacher.subject); } }
public class PrototypeDemo { public static void main(String[] args) throws CloneNotSupportedException{ ArrayList<String> style = new ArrayList<>(); style.add("中原建造风格"); style.add("西部建造风格"); System.out.println("-------浅拷贝-------"); School school = new School("中原大学"); school.setSummary("河南省中原路1号",style); school.setTeacher("八年教学经验","unix内核高级编程"); //浅拷贝 School school1 = school.clone(); school1.setTeacher("两年教学经验","高等数学"); school.display(); school1.display(); System.out.println("-------深拷贝-------"); School2 school2 = new School2("中原大学"); school2.setSummary("河南省中原路1号",style); school2.setTeacher("八年教学经验","unix内核高级编程"); //深拷贝 School2 school3 = school2.clone(); school3.setTeacher("两年教学经验","高等数学"); school2.display(); school3.display(); } }