大话设计模式——8.原型模式(Prototype Pattern)
public class Student implements Cloneable, Serializable {
private String name;
private String sex;
/**
* 年级
*/
private String grade;
/**
* 学校
*/
private String schoolName;
/**
* 学科
*/
private List<String> subjects;
/**
* 浅拷贝 ,调用*父类Object的方法
*
* @return
* @throws CloneNotSupportedException
*/
@Override
protected Student clone() throws CloneNotSupportedException {
return (Student) super.clone();
}
/**
* 深拷贝
*
* @return
*/
public Student deepClone() {
try {
// 转换二进制输出流,序列化
ByteArrayOutputStream bao = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bao);
oos.writeObject(this);
// 输入流转换,反序列化,拷贝形成新的对象
ByteArrayInputStream bai = new ByteArrayInputStream(bao.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bai);
return (Student) ois.readObject();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public Student() {
}
public Student(String name, String sex, String grade, String schoolName, List<String> subjects) {
this.name = name;
this.sex = sex;
this.grade = grade;
this.schoolName = schoolName;
this.subjects = subjects;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public String getSchoolName() {
return schoolName;
}
public void setSchoolName(String schoolName) {
this.schoolName = schoolName;
}
public List<String> getSubjects() {
return subjects;
}
public void setSubjects(List<String> subjects) {
this.subjects = subjects;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", sex='" + sex + '\'' +
", grade='" + grade + '\'' +
", schoolName='" + schoolName + '\'' +
", subjects=" + subjects +
'}';
}
}