原型模式

来源:互联网 发布:java技术交流论坛 编辑:程序博客网 时间:2024/06/07 03:13
public class Student implements Cloneable{private String name;private String code;public String getName() {return name;}public void setName(String name) {this.name = name;}public String getCode() {return code;}public void setCode(String code) {this.code = code;}@Overridepublic String toString() {return "Student [name=" + name + ", code=" + code + "]";}@Overrideprotected Object clone() throws CloneNotSupportedException {return (Student)super.clone();}}

public class School implements Cloneable{private String name;private String address;private Student student;public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}public String getName() {return name;}public void setName(String name) {this.name = name;}@Overrideprotected Object clone() throws CloneNotSupportedException {School school = new School();school.setName(name);school.setAddress(address);school.setStudent((Student)student.clone());return school;}@Overridepublic String toString() {return "School [name=" + name + ", address=" + address + ", student=" + student + "]";}public Student getStudent() {return student;}public void setStudent(Student student) {this.student = student;}}


客户实现

public static void main(String[] args) throws CloneNotSupportedException{School a = new School();a.setName("school1");a.setAddress("address1");Student student = new Student();student.setName("wcp");student.setCode("12");a.setStudent(student);School b = (School) a.clone();b.setName("school2");student.setName("wcp1");System.out.println(a.toString());System.out.println(b.toString());}

运行结果

School [name=school1, address=address1, student=Student [name=wcp1, code=12]]School [name=school2, address=address1, student=Student [name=wcp, code=12]]


原创粉丝点击