# Java设计模式-原型模式
## 概念
原型模式(Prototype Pattern)是用于创建重复的对象,同时又能保证性能。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
这种模式是实现了一个原型接口,该接口用于创建当前对象的克隆。当直接创建对象的代价比较大时,则采用这种模式。例如,一个对象需要在一个高代价的数据库操作之后被创建。我们可以缓存该对象,在下一个请求时返回它的克隆,在需要的时候更新数据库,以此来减少数据库调用。
- 由原型对象自身创建目标对象。也就是说,对象创建这一动作发自原型对象本身。
- 目标对象是原型对象的一个克隆。也就是说,通过原型模式创建的对象,不仅仅与原型对象具有相同的结构,还与原型对象具有相同的值。
- 根据对象克隆深度层次的不同,有浅度克隆与深度克隆。
## 使用场景
- 在创建对象的时候,我们不只是希望被创建的对象继承其基类的基本结构,还希望继承原型对象的数据。
- 希望对目标对象的修改不影响既有的原型对象(深度克隆的时候可以完全互不影响)。
- 隐藏克隆操作的细节,很多时候,对对象本身的克隆需要涉及到类本身的数据细节。
- 类初始化需要**消耗非常多的资源**,这个资源包括数据、硬件资源等;
- 通过 new 产生一个对象需要非常繁琐的数据准备或访问权限,则可以使用原型模式;
- 一个对象需要提供给其他对象访问,而且各个调用者可能都需要修改其值时,可以考虑使用原型模式拷贝多个对象供调用者使用。在实际项目中,原型模式很少单独出现,一般是和**工厂方法模式**一起出现,通过 clone的方法创建一个对象,然后由工厂方法提供给调用者。原型模式先产生出一个包含大量共有信息的类,然后可以拷贝出副本,修正细节信息,建立了一个完整的个性对象。
## 模式结构
原型模式包含如下角色:
- Prototype:抽象原型类
- ConcretePrototype:具体原型类
- (可选)工厂缓存类
- Client:客户类
## 优缺点
### 优点
1. 性能提高。 当创建新的对象实例较为复杂时,使用原型模式可以简化对象的创建过程,通过一个已有实例可以提高新实例的创建效率。
2. 简化了创建结构,逃避构造函数的约束。
3. 可以使用深克隆的方式保存对象的状态。
### 缺点
1. 配备克隆方法需要对类的功能进行通盘考虑,这对于全新的类不是很难,但对于已有的类不一定很容易,特别当一个类引用不支持串行化的间接对象,或者引用含有循环结构的时候。
2. 必须实现 Cloneable 接口
## 案例一
先写一个支持克隆的类
```
1 //如果要克隆就必须实现Cloneable接口
2 public class Person implements Cloneable{
3 //可能会抛出不支持克隆异常,原因是没有实现Cloneable接口
4 @Override
5 protected Person clone(){
6 try{
7 return (Person) super.clone();
8 }catch(CloneNotSupportedException e){
9 e.printStackTrace();
10 return null;
11 }
12 }
13 }
```
```
1 public class MainClass {
2 public static void main(String[] args) {
3 Person person1 = new Person();
4
5 Person person2 = person1.clone();
6 }
7 }
```
克隆是复制出一份一模一样的对象,两个对象内存地址不同,但对象中的结构与属性值一模一样。
**对象拷贝时,类的构造函数是不会被执行的**。Object 类的 clone 方法的 原理是从内存中(具体的说就是堆内存)以二进制流的方式进行拷贝,重新分配一个内存块。
### 深克隆和浅克隆
#### 浅克隆
- 当被克隆的类中有引用对象**(String或Integer等包装类型除外)**时,克隆出来的类中的引用变量存储的还是之前的内存地址,也就是说克隆与被克隆的对象是同一个。这样的话两个对象**共享了一个私有变量**,所有人都可以改,是一个种非常不安全的方式。
```
1 //如果要克隆就必须实现Cloneable接口
2 public class Person implements Cloneable{
3 private String name;
4 private String sex;
5 private List<String> list;
6 public String getName() {
7 return name;
8 }
9 public void setName(String name) {
10 this.name = name;
11 }
12 public String getSex() {
13 return sex;
14 }
15 public void setSex(String sex) {
16 this.sex = sex;
17 }
18 public List<String> getList() {
19 return list;
20 }
21 public void setList(List<String> list) {
22 this.list = list;
23 }
24 //可能会抛出不支持克隆异常,原因是没有实现Cloneable接口
25 @Override
26 protected Person clone(){
27 try{
28 return (Person) super.clone();
29 }catch(CloneNotSupportedException e){
30 e.printStackTrace();
31 return null;
32 }
33 }
34 }
```
#### 深克隆
只需要把clone方法修改成如下:
```
24 //可能会抛出不支持克隆异常,原因是没有实现Cloneable接口
25 @Override
26 protected Person clone(){
27 try{
28 Person person = (Person) super.clone();
29 List<String> newList = new ArrayList();
30
31 for(String str : this.list){
32 newList.add(str);
33 }
34 person.setList(newList);
35 return person;
36 }catch(CloneNotSupportedException e){
37 e.printStackTrace();
38 return null;
39 }
40 }
```
这样就完成了深度拷贝,两种对象互为独立,属于单独对象。
## 案例二
Prototype:抽象原型类
```
public abstract class Shape implements Cloneable {
private String id;
protected String type;
abstract void draw();
public String getType(){
return type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Object clone() {
Object clone = null;
try {
clone = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return clone;
}
}
```
ConcretePrototype:具体原型类
```
public class Rectangle extends Shape {
public Rectangle(){
type = "Rectangle";
}
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
```
```
public class Square extends Shape {
public Square(){
type = "Square";
}
@Override
public void draw() {
System.out.println("Inside Square::draw() method.");
}
}
```
```
public class Circle extends Shape {
public Circle(){
type = "Circle";
}
@Override
public void draw() {
System.out.println("Inside Circle::draw() method.");
}
}
```
创建一个类,从数据库获取实体类,并把它们存储在一个 *Hashtable* 中。即把较为复杂的操作,先缓存在类似于工厂类中
ShapeCache缓存类:
```
import java.util.Hashtable;
public class ShapeCache {
private static Hashtable<String, Shape> shapeMap
= new Hashtable<String, Shape>();
public static Shape getShape(String shapeId) {
Shape cachedShape = shapeMap.get(shapeId);
return (Shape) cachedShape.clone();
}
// 对每种形状都运行数据库查询,并创建该形状
// shapeMap.put(shapeKey, shape);
// 例如,我们要添加三种形状
public static void loadCache() {
Circle circle = new Circle();
circle.setId("1");
shapeMap.put(circle.getId(),circle);
Square square = new Square();
square.setId("2");
shapeMap.put(square.getId(),square);
Rectangle rectangle = new Rectangle();
rectangle.setId("3");
shapeMap.put(rectangle.getId(),rectangle);
}
}
```
使用时只需要通过上述工厂类来获取指定类型的实例的clone
```
public class PrototypePatternDemo {
public static void main(String[] args) {
ShapeCache.loadCache();
Shape clonedShape = (Shape) ShapeCache.getShape("1");
System.out.println("Shape : " + clonedShape.getType());
Shape clonedShape2 = (Shape) ShapeCache.getShape("2");
System.out.println("Shape : " + clonedShape2.getType());
Shape clonedShape3 = (Shape) ShapeCache.getShape("3");
System.out.println("Shape : " + clonedShape3.getType());
}
}
```
参考:
https://en.wikipedia.org/wiki/Prototype_pattern
https://www.cnblogs.com/xiaobai1226/p/8488332.html
http://www.runoob.com/design-pattern/prototype-pattern.html