###原型模式 ####原型模式的優勢 原型模式建立對象比直接使用new建立對象性能上要好許多,爲Object類的clone方法是一個本地方法,它直接操做的是內存中的二進制流.原型模式簡化建立對象的過程,使得建立對象像粘貼複製同樣.ide
####使用場景 須要重複地建立類似對象時能夠考慮使用原型模式,好比在一個循環體類建立對象.性能
####代碼實現:this
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(); } } }
####原型模式的注意點prototype
使用原型模式不會調用類的構造方法.code
深拷貝和淺拷貝 淺拷貝: 對值類型的成員變量進行值的複製,對引用類型的成員變量只複製引用,不復制引用的對象. 深拷貝: 對值類型的成員變量進行值的複製,對引用類型的成員變量也進行引用對象的複製.對象
#####淺拷貝內存
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改變
#####深拷貝get
@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改變