设计模式(5)---原型模式

原型模式  Prototype(创建型模式)

1.概述

所谓原型模式就是用原型实例指定创建对象的种类,并且通过复制这些原型创建新的对象。

2.例子

School类

 1 public class School {
 2 
 3     String schoolName ;
 4     String adress ;
 5     
 6     public School(String schoolName, String adress) {
 7         super();
 8         this.schoolName = schoolName;
 9         this.adress = adress;
10     }
11 
12     public String getSchoolName() {
13         return schoolName;
14     }
15 
16     public void setSchoolName(String schoolName) {
17         this.schoolName = schoolName;
18     }
19 
20     public String getAdress() {
21         return adress;
22     }
23 
24     public void setAdress(String adress) {
25         this.adress = adress;
26     }
27 
28     public School() {
29         // TODO Auto-generated constructor stub
30     }
31 
32 }
View Code

Person类

 1 public class Person implements Cloneable {
 2 
 3     String name ;
 4     int age ;
 5     School school ;
 6     
 7     public School getSchool() {
 8         return school;
 9     }
10 
11     public void setSchool(School school) {
12         this.school = school;
13     }
14 
15     public String getName() {
16         return name;
17     }
18 
19     public void setName(String name) {
20         this.name = name;
21     }
22 
23     public int getAge() {
24         return age;
25     }
26 
27     public void setAge(int age) {
28         this.age = age;
29     }
30 
31     public Person() {
32         // TODO Auto-generated constructor stub
33     }
34     
35     public Person clone(){
36         Person person = null;
37         try {
38             person = (Person) super.clone();
39         } catch (CloneNotSupportedException e) {
40             e.printStackTrace();
41         }
42         return person;
43     }
44 
45 }
 1 public class Test {
 2 
 3     public static void main(String[] args) {
 4         Person a = new Person() ;
 5         a.setName("张三");
 6         a.setAge(20);
 7         
 8         School school = new School("xx学校","xx路xx号");
 9         a.setSchool(school);
10         
11         //输出   张三20   xx学校
12         System.out.println(a.getName()+a.getAge()+"   "+a.getSchool().getSchoolName());
13         
14         Person b = a.clone() ;
15         //输出   张三20   xx学校
16         System.out.println(b.getName()+b.getAge()+"   "+b.getSchool().getSchoolName());
17         
18         school.setSchoolName("yy学校");
19         //输出   张三20   yy学校
20         System.out.println(a.getName()+a.getAge()+"   "+a.getSchool().getSchoolName());
21         //输出   张三20   yy学校
22         System.out.println(b.getName()+b.getAge()+"   "+b.getSchool().getSchoolName());
23 
24     }
25 
26 }

3.浅拷贝和深拷贝

Object类的clone方法只会拷贝对象中的基本的数据类型,对于数组、容器对象、引用对象等都不会拷贝,这就是浅拷贝。如果要实现深拷贝,必须将原型模式中的数组、容器对象、引用对象等另行拷贝。

比如上面例子,改变了学校名称之后,对象a,b的学校名称都会改变,说明这两个对象中的School引用指向的是同一个对象。

4.优点

在需要重复地创建相似对象时可以考虑使用原型模式。比如需要在一个循环体内创建对象,假如对象创建过程比较复杂或者循环次数很多的话,使用原型模式不但可以简化创建过程,而且可以使系统的整体性能提高很多。

原文地址:https://www.cnblogs.com/mengchunchen/p/5741448.html