原型设计模式(Prototype Pattern)
描述: 它是用来创建重复对象的,首先创建一个实例然后通过这个实例拷贝创建新的实例
核心思想: 使用克隆的方式进行对象的创建
使用场景:
原型设计模式的优点:
原型设计模式的缺点:
- 引用含有循环引用如何处理
- 必须实现 Cloneable 接口。
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| class student implements Cloneable { private String name; private Integer age;
@Override public Object clone() { Object clone = null; try { clone = super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return clone; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class teacher implements Cloneable { private String name; private Integer age; private String sex;
private student stu; @Override public Object clone() { Object clone = null; try { clone = super.clone(); student clone1 = (student) this.getStu().clone(); this.setStu(clone1); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return clone; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| public static void main(String[] args) { teacher tea = new teacher(); tea.setName("老师"); student student = new student(); student.setAge(33); student.setName("学生"); tea.setAge(56); tea.setSex("男"); tea.setStu(student);
teacher clone = (teacher) tea.clone(); clone.setAge(78); clone.setName("克隆老师"); clone.getStu().setAge(99); clone.getStu().setName("小学生");
System.out.println(tea); System.out.println(clone); } }
|
1 2
| teacher(name=老师, age=56, sex=男, stu=student(name=学生, age=33)) teacher(name=克隆老师, age=78, sex=男, stu=student(name=小学生, age=99))
|