原型模式(Prototype Pattern)是用于建立重复的对象,同时又能保证性能。这种类型的设计模式属于建立型模式,它提供了一种建立对象的最佳方式。数据库
这种模式是实现了一个原型接口,该接口用于建立当前对象的克隆。当直接建立对象的代价比较大时,则采用这种模式。例如,一个对象须要在一个高代价的数据库操做以后被建立。咱们能够缓存该对象,在下一个请求时返回它的克隆,在须要的时候更新数据库,以此来减小数据库调用。设计模式
如今想来,实际开发过程当中极少应用这一模式,在于Spring
已经帮咱们实现了。
当咱们须要调用对象时,经常只需@Autowired
。缓存
意图
用原型实例指定建立对象的种类,而且经过拷贝这些原型建立新的对象。安全
主要解决
在运行期创建和删除原型。ide
如何解决
利用已有的一个原型对象,快速地生成和原型对象同样的实例。函数
Cloneable
接口。@transactional
方法还没有结束,又想对因执行save、update
等方法的对象,进行修改。注意事项:与经过对一个类进行实例化来构造新对象不一样的是,原型模式是经过拷贝一个现有对象生成新对象的。浅拷贝实现 Cloneable
,重写,深拷贝是经过实现 Serializable
读取二进制流。性能
public class Message implements Cloneable{ private Integer id; private String phone; private String token; private String verificationCode; private Date verifiedAt; private String ipAddress; private Date createdAt; private Date updatedAt; public Message() { } public Message(String phone, String ipAddress, String token) { this.phone = phone; this.ipAddress = ipAddress; this.token = token; } /** * 利用GenerateCopyConstructor插件生成 */ public Message(Message other) { this.id = other.id; this.phone = other.phone; this.token = other.token; this.verificationCode = other.verificationCode; this.verifiedAt = other.verifiedAt; this.ipAddress = other.ipAddress; this.createdAt = other.createdAt; this.updatedAt = other.updatedAt; } @Override public Message clone() { return new Message(this); } public Message(String phone, String ipAddress, String token, String verificationCode) { this.phone = phone; this.ipAddress = ipAddress; this.token = token; this.verificationCode = verificationCode; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } ....... }
提示:若是是使用idea,能够利用GenerateCopyConstructor插件,协助生成
(在此略去插件安装过程)优化
Generate...
,Mac 快捷键Commond + n
,Windows快捷键Alt + Insert
Copy Constructor
利用BeanUtils实现this