Skip to content

Instantly share code, notes, and snippets.

@codejets
Last active March 21, 2016 08:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codejets/e4efebfdd11cfaeaf339 to your computer and use it in GitHub Desktop.
Save codejets/e4efebfdd11cfaeaf339 to your computer and use it in GitHub Desktop.
flyweight pattern
// Flyweight Pattern
/*
Here we are sharing a part of our data into a separate object.
*/
(function() {
'use strict';
// Usual constructor method
function Book(data) {
this.flyweight = BookFlyweight.get(data.genres, data.language, data.ratings, data.types);
this.name = data.name;
this.author = data.author;
}
var BookFlyweight = function() {
var flyweights = {};
var get = function(genres, language, ratings, types) {
if (!flyweights[genres+language+ratings+types]) {
flyweights[genres+language+ratings+types] =
new Flyweight(genres,language,ratings,types);
}
return flyweights[genres+language+ratings+types];
}
var getCount = function() {
var count = 0;
for (var c in flyweights) {
count++;
}
return count;
}
return {
get: get,
getCount: getCount,
}
}()
/*
These are the shared values.
*/
function Flyweight(genres, language, ratings, types) {
this.genres = genres;
this.language = language;
this.ratings = ratings;
this.types = types;
}
var BookCollection = function() {
var books = {}, count = 0;
var add = function(data) {
books[data.name] = new Book(data);
count++;
}
var getCount = function() {
return count;
}
return {
add: add,
getCount: getCount,
}
}
var books = new BookCollection();
// Defining the limits of shared data.
var genres = [ 'mystery', 'fantasy', 'romance', 'sci-fi'];
var language = [ 'Eng', 'Fre', 'Spa', 'Jp', 'Others'];
var ratings = [ '1', '2', '3', '4', '5'];
var types = [ 'AudioBook', 'Ebook', 'Print'];
for (var i = 0; i < 10000; i++) {
books.add({
name: 'book'+i,
author: 'author'+i,
genres : genres[Math.floor((Math.random() * 4))],
language : language[Math.floor((Math.random() * 5))],
ratings : ratings[Math.floor((Math.random() * 5))],
types : types[Math.floor((Math.random() * 3))]
});
}
console.log(books.getCount()); // 10000
console.log(BookFlyweight.getCount()); // 300
/*
BookFlyweight.getCount() will give the number of shared
flyweight that these records have. for 1000 we get 300
flyweight at random. With increased complexity this technique
can really increase efficiency.
*/
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment