# 原型模式

原型模式 Prototype 使用一个已经创建的示例作为原型，通过复制该原型对象来创建一个和原型对象相同的新的对象。JavaScript就是一个纯面向对象语言，JS基于原型面向对象，它通过对象来创建对象。

主要解决的问题：

1. 创建对象成本较大，比如对象种的数据是经过复杂的计算才能得到，或者需要经过rpc接口或者数据等比较慢的io中获取的，这种情况推荐使用原型模式，从已有的对象中进行拷贝，而不是每次都创建新的对象，进行一些耗时操作。

> BufferedImage读取背景图过慢，是否可以通过这种方式来加快对象的创建?

![picture 1](/files/h4IfN69qPDFHdxAIMCLv)

## 使用场景

1. 资源优化场景
2. 复杂的依赖场景
3. 性能与安全要求的场景
4. 同一个对象可能被修改者使用的场景
5. 需要保存原始状态的状态时

## 浅克隆

克隆对象中的所有变量的值与原型对象的值完全相同：

1. 基本数据类型值复制
2. 引用数据类型引用复制

实现浅克隆：

1. 实现Cloneable接口，调用clone复制

## 深克隆

1. 基本类型值复制
2. 引用数据类型递归复制引用对象的内容

实现深克隆：

1. 实现Serivalizable接口，使用ObjectOuptStream写入对象，再使用 ObjectInputStream读取对象，新读取的对象就是一个深克隆对象
2. 使用json、xml等其他序列化


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://yangsx95.gitbook.io/notes/computer-science/she-ji-mo-shi/yuan-xing-mo-shi.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
