原型模式(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