原型模式
字数: 0

基本概念

Prototype Pattern: (GoF Definition) Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
In general, creating a new instance from scratch is a costly operation. Using the prototype pattern, you can create new instances by copying or cloning an instance of an existing one. This approach saves both time and money in creating a new instance from scratch.
notion image
例如,一个对象需要在一个高代价的数据库操作之后被创建,则可以通过缓存该对象,在下一个请求时返回它的克隆,减少数据库调用。

浅拷贝

Shallow Copy creates a new object and then copies various field values from the original object to the new object. So, it is also known as a field-by-field copy. It copies only the references, not the actual objects.
复制的是对象本身以及其所有直接引用的字段,而不会递归地复制对象引用的其他对象
Object 类提供了clone() 方法,用于创建对象的浅拷贝。
  • 类必须显式实现 Cloneable 接口,否则在调用 clone()方法时会抛出CloneNotSupportedException异常。
  • 可以重写 clone() 方法。如果不需要执行自定义操作,默认直接 super.clone()
notion image

深拷贝

Deep Copy creates a new object but recursively copies all fields and sub-objects from the original object. It ensures that the entire object tree is completely new, with no shared references.
复制的是对象以及其引用的所有对象,包括直接引用的对象、间接引用的对象。
深拷贝通常比浅拷贝更复杂和耗时,它需要遍历整个对象图并复制每个对象。通常需要开发者自行编写代码来实现。
多个对象的深拷贝是相互独立的,它们之间没有共享的引用对象,因此完全隔离。

实现代码

原型

定义了克隆方法的抽象接口或类

具体原型

Concrete Prototype, 实现了原型接口的具体类

测试类

Q & A

When I copy an object in Java, I need to use the clone() method. Is this understanding correct?
  • No. There are alternatives available, and one of them is to use the serialization mechanism. But you can always define your own copy constructor and use it. 序列化机制将对象的状态转换为字节流,稍后可以通过反序列化字节流重建对象的状态。
  • BeanUtils.copyProperties()
 
2023 - 2026