设计模式之原型模式 - 深拷贝和浅拷贝
设计模式 Java 面试 大约 2086 字作用
用原型实例指定创建对象的种类,并且通过拷贝这些原型来创建新的对象。
案例
浅拷贝
- 实现Cloneable
- 重写clone方法
- 能拷贝基础类型及String
- 不能拷贝引用类型
public class Prototype implements Cloneable {
@Override
protected Prototype clone() throws CloneNotSupportedException {
return (Prototype) super.clone();
}
}
深拷贝
- 实现Serializable、Cloneable
- 使用ByteArrayOutputStream/ObjectOutputStream/ByteArrayInputStream/ObjectInputStream
public class DeepClonePrototype implements Serializable, Cloneable {
public Helper helper;
public DeepClonePrototype deepClone() throws Exception {
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos)) {
oos.writeObject(this);
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
return (DeepClonePrototype) ois.readObject();
}
}
}
class Helper implements Serializable {
}
运行结果
//create.prototype.Prototype@4554617c
//create.prototype.Prototype@74a14482
//--------------
//create.prototype.DeepClonePrototype@1540e19d
//create.prototype.Helper@677327b6
//create.prototype.DeepClonePrototype@7ef20235
//create.prototype.Helper@27d6c5e0
public static void main(String[] args) throws Exception {
Prototype prototype = new Prototype();
System.out.println(prototype);
Prototype clone = prototype.clone();
System.out.println(clone);
System.out.println("--------------");
DeepClonePrototype deepClonePrototype = new DeepClonePrototype();
Helper helper = new Helper();
deepClonePrototype.helper = helper;
System.out.println(deepClonePrototype);
System.out.println(helper);
DeepClonePrototype clone2 = deepClonePrototype.deepClone();
System.out.println(clone2);
System.out.println(clone2.helper);
}
源码
org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean
Spring
框架注入bean
对象时指定scope
为prototype
。
注解指定:@Scope("prototype")
xml
配置指定:
<bean id="jedisUtil" class="com.demo.util.JedisUtil" scope="prototype"/>
阅读 1346 · 发布于 2019-12-16
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看
换一批
-
JMeter 提取 JSON 字段用于下一个请求阅读 685
-
设计模式之状态设计模式阅读 859
-
Spring 组件的注册时机阅读 381
-
Spring Boot 使用 @Valid 校验前端传递的参数阅读 3646
-
使用 Spring Boot Admin 管理 Spring Boot 应用阅读 1297
-
软考-系统架构设计师:逆向工程阅读 1336
-
Android 仿 iOS 删除时抖动效果阅读 2999
-
数据结构:2-3树、B树、B+树、B*树阅读 1185
-
Prometheus+Grafana+redis_exporter 监控 Redis 服务阅读 308
-
MySQL5.7 搭建主从-传统方式阅读 598