概念
原型模式是特殊的创建模式,它创建对象不通过直接new的方式产生,而是通过已有的对象复制。
实现
浅拷贝
- 类图:
Product
1 | public class Product implements Serializable { |
ProductB
1 | public class ProductB implements Serializable { |
Client
1 | public class Client { |
执行结果:
Connected to the target VM, address: ‘127.0.0.1:58904’, transport: ‘socket’
product name:X
product value:XX
productB name:B
product name:X
product value:XX
productB name:newXX
Disconnected from the target VM, address: ‘127.0.0.1:58904’, transport: ‘socket’
深拷贝
- 类图:
Product
1 | public class Product implements Cloneable { |
ProductB
1 | public class ProductB { |
Client
1 | public class Client { |
执行结果:
Connected to the target VM, address: ‘127.0.0.1:58962’, transport: ‘socket’
product name:X
product value:XX
productB name:newXX
product name:X
product value:XX
productB name:newXX
Disconnected from the target VM, address: ‘127.0.0.1:58962’, transport: ‘socket’
场景
总结
浅拷贝 拷贝后的对象如果有嵌套的复杂对象,那么改变嵌套对象会跟着改变。只拷贝表层的对象信息。
深拷贝,是所有的都拷贝,包括嵌套对象。这里的实现是通过序列化的方式实现。