###原型模式 ####原型模式的优点 原型模式创建对象比直接使用new创建对象性能上要好许多,为Object类的clone方法是一个本地方法,它直接操作的是内存中的二进制流.原型模式简化创建对象的过程,使得创建对象像粘贴复制一样.
####使用场景 需要重复地创建相似对象时可以考虑使用原型模式,比如在一个循环体类创建对象.
####代码实现:
public class Prototype implements Cloneable{
public Prototype clone(){
Prototype prototype = null;
try {
prototype = (Prototype) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return prototype;
}
}
public class ConcretePrototype extends Prototype {
public void show(){
System.out.println("原型模式实现类:");
}
}
public class Client {
public static void main(String[] args) {
ConcretePrototype cp = new ConcretePrototype();
for (int i = 0; i < 10; i++) {
ConcretePrototype clonecp = (ConcretePrototype) cp.clone();
clonecp.show();
}
}
}
####原型模式的注意点
-
使用原型模式不会调用类的构造方法.
-
深拷贝和浅拷贝 浅拷贝: 对值类型的成员变量进行值的复制,对引用类型的成员变量只复制引用,不复制引用的对象. 深拷贝: 对值类型的成员变量进行值的复制,对引用类型的成员变量也进行引用对象的复制.
#####浅拷贝
import lombok.Data;
@Data
public class Student implements Cloneable{
private String studentName;
private Teacher teacher;
@Override
protected Student clone() throws CloneNotSupportedException {
return (Student) super.clone();
}
public Student(String studentName, Teacher teacher) {
this.studentName = studentName;
this.teacher = teacher;
}
}
@Data
public class Teacher implements Serializable {
private static final long UID = 6948989635489677685L;
private String name;
public Teacher(String name) {
this.name = name;
}
}
public class Client {
public static void main(String[] args) throws Exception {
Teacher teacher = new Teacher("snail");
Student student1 = new Student("wjk",teacher);
Student student2 = (Student) student1.clone();
student2.getTeacher().setName("snail改变");
System.out.println(student1.getTeacher().getName());
System.out.println(student2.getTeacher().getName());
}
}
**运行结果**(拷贝的是引用)
snail改变
snail改变
#####深拷贝
@Data
public class StudentSh implements Serializable {
private static final long UID = 6948989635489677685L;
private String studentName;
private Teacher teacher;
public StudentSh(String studentName, Teacher teacher) {
this.studentName = studentName;
this.teacher = teacher;
}
public Object deepClone() {
try {
//将对象写到流里
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream oo = new ObjectOutputStream(bo);
oo.writeObject(this);
//从流里读出来
ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
ObjectInputStream oi = new ObjectInputStream(bi);
return (oi.readObject());
} catch (Exception e) {
return null;
}
}
}
public class Client {
public static void main(String[] args) throws Exception {
Teacher teacher = new Teacher("snail");
StudentSh student1 =new StudentSh("wjk",teacher);
StudentSh student2 = (StudentSh) student1.deepClone();
student2.getTeacher().setName("snail改变");
System.out.println(student1.getTeacher().getName());
System.out.println(student2.getTeacher().getName());
}
}
**运行结果**
snail
snail改变