设计模式 -- 原型模式
介绍
-
原型模式(Prototype Pattern)是用于创建重复的对象,同时又能保证性能
-
核心
1. 实现Cloneable接口,该接口的作用是通知虚拟机可以安全使用实现该接口的类的clone()方法 2. 重写clone()方法
-
注意:在java中,只有实现了该接口才能被拷贝,否则抛出
java.lang.CloneNotSupportedException
异常
使用场景
-
资源优化
-
类初始化需要消化非常多的资源,这个资源包括数据、硬件资源等
-
通过 new 产生一个对象需要非常繁琐的数据准备或访问权
-
一个对象需要提供给其他对象访问,而且各个调用者可能都需要修改其值时
案例
-
创建
Student
类,实现Cloneable
接口,重写clone()
方法public class Student implements Cloneable{ private String name; private Integer age; private School school; private Student student = null; public Student(String name, Integer age, School school) { this.name = name; this.age = age; this.school = school; } @Override protected Object clone() throws CloneNotSupportedException { // 对基本数据类型和string的拷贝 student = (Student) super.clone(); // 对引用类型进行拷贝(深拷贝) student.school = (School) this.school.clone(); return student; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public School getSchool() { return school; } public void setSchool(School school) { this.school = school; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + ", school=" + school + '}'; } }
-
创建
School
类,实现Cloneable
接口,重写clone()
方法public class School implements Cloneable{ private String addr; private String classroom; public School(String addr,String classroom){ this.addr = addr; this.classroom = classroom; } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } @Override public String toString() { return "School{" + "addr='" + addr + '\'' + ", classroom='" + classroom + '\'' + '}'; } }
-
编写测试类
public class Test { public static void main(String[] args) throws CloneNotSupportedException { School school = new School("二中","初一三班"); Student mike = new Student("mik1",15,school); System.out.println(mike.toString()); System.out.println("Mike升到了高中"); Student mike2 = (Student) mike.clone(); School school2 = new School("一中","高三六班"); mike2.setSchool(school2); mike2.setAge(20); System.out.println(mike2.toString()); } }
运行结果