JAVA设计模式——原型模式

原型模式:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

原型模式其实就是从一个对象再创建另外一个可定制的对象,而且不需要知道任何创建的细节。

一般在初始化的信息不发生变化的情况下,克隆是最好的办法。这既隐藏了对象创建的细节,又对性能是大大的提高。相当于不用重新初始化对象,而是动态地获得对象运行时的状态。

clone()方法 如果对象是数值类型,复制的是内容,引用类型则复制地址。
浅复制:被复制对象的所有变量都含有与原来的对象相同的值,而所有的对其他对象的引用都仍然指向原来的对象。clone()
深复制:把引用对象的变了指向复制过的新对象,而不是原有的被引用的对象。copy()

这里写图片描述

public class Classroom implements Serializable {
private Student student;
private String name;
public Classroom() {
}
public Classroom(Student student) {
this.student = student;
}
public Classroom(Student student, String name) {
this.student = student;
this.name = name;
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
//使用序列化技术实现深克隆
protected Classroom deepClone() throws IOException, CloneNotSupportedException, ClassNotFoundException {
//将对象写入流中
ByteArrayOutputStream bao = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bao);
oos.writeObject(this);
//将对象从流中取出
ByteArrayInputStream bis = new ByteArrayInputStream(bao.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
return (Classroom)ois.readObject();
}
}

public class Student implements Serializable {
private String name;
public Student() {
}
public Student(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
protected Student clone() throws CloneNotSupportedException {
Object obj = null;
try {
obj = super.clone();
return (Student)obj;
} catch (CloneNotSupportedException e) {
e.printStackTrace();
return null;
}
}
}

public class Main {
public static void main(String[] args) throws CloneNotSupportedException, IOException, ClassNotFoundException {
Student student = new Student(“张三”);
Classroom classroom = new Classroom(student,”一班”);
Classroom classroom1 = classroom.deepClone();
System.out.println(classroom.getStudent() == classroom1.getStudent()); //false
System.out.println(classroom == classroom1); //false
}
}

猜你喜欢

转载自blog.csdn.net/qq_36997245/article/details/81711847