本文以一個圖書館藏書與借書的情境,示範如何在 JavaScript 中實現享元(Flyweight)模式,透過共用物件來節省記憶體。
<!DOCTYPE html>
<html>
<head>
<title>享元模式</title>
</head>
<body>
<script>
/*
* flyweight 享元模式
*/
// 例子是一個圖書館存書借書
var Book = function(id, title, author, genre, pageCount, publisherId, ISBN, checkoutDate, checkoutMember /*還有一些*/){
this.id = id;
this.title = title;
this.author = author;
this.genre = this.genre;
this.pageCount = pageCount;
this.publisherId = publisherId;
this.ISBN = ISBN;
/*...*/
this.checkoutDate = checkoutDate;
this.checkoutMember = checkoutMember;
};
Book.prototype = {
getTitle : function(){ return this.title; },
getAuthor : function(){ return this.author; },
getISBN : function(){ return this.ISBN; },
updateCheckoutStatus : function(bookId, checkoutDate, checkoutMember){
this.id = bookId;
this.checkoutDate = checkoutDate;
this.checkoutMember = checkoutMember;
}
};
// 下面介紹享元的版本:用一個物件來存放書籍,這樣就可以共用同一本書
var BookFactory = (function(){
var existingBooks = {}, existingBook;
return {
createBook : function(title, author, genre, ISBN){
existingBook = existingBooks[ISBN];
if(existingBook){
return existingBook;
}else{
var book = new Book(/*更多書籍資訊*/);
return existingBooks[ISBN] = book;
}
}
}
})();
var BookRecordManager = (function(){
var bookRecordDatabase = {};
return {
addBookRecord : function(id, ISBN /*==*/){
var book = BookFactory.createBook(/**/);
bookRecordDatabase[id] = {
checkoutDate : checkoutDate,
checkoutMember : checkoutMember
};
},
updateCheckoutStatus : function(bookId, xx){
bookRecordDatabase[bookId] = { xx : tt, oo : yy };
},
extend : function(){
/*自訂各種公用方法*/
}
}
})();
</script>
</body>
</html>
關鍵在於 BookFactory 以 ISBN 為鍵快取已建立的書籍物件,讓相同的書只被建立一次,其餘的借閱狀態則獨立記錄在 BookRecordManager 中。