一、什么是原型模式
Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
《设计模式:可复用面向对象软件的基础》
原型模式个人理解,其实就是用标准的方法克隆当前对象。
二、原型模式如何实施
下面是一个原型模式的实现用例,其实也可以基于json、基于setter等等都可以,这些只是实施的具体方法,思想是相同即可。
1. 实现类
import org.apache.commons.lang3.SerializationUtils;
import java.io.Serializable;
import java.util.List;
public class BeanPrototype implements Cloneable, Serializable {
private Integer id;
private String name;
private List<String> attributes;
public BeanPrototype(Integer id, String name, List<String> attributes) {
this.id = id;
this.name = name;
this.attributes = attributes;
}
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public List<String> getAttributes() {
return attributes;
}
@Override
public BeanPrototype clone() {
return SerializationUtils.clone(this);
}
}
2. 使用
BeanPrototype bean = new BeanPrototype(1,"名称", new LinkedList<>());
BeanPrototype clone = bean.clone();//深拷贝
三、使用场景
- Spring的org.springframework.beans.factory.support.AbstractBeanDefinition#clone就是一个基于setter进行的深拷贝