Created
October 29, 2017 19:31
-
-
Save nitin42/b27c33242a4c1c1ed4b8bd1cb58ae242 to your computer and use it in GitHub Desktop.
Flyweight pattern in a nutshell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Flyweight (make, model, processor) { | |
this.make = make; | |
this.model = model; | |
this.processor = processor; | |
}; | |
var FlyWeightFactory = (function () { | |
var flyweights = {}; | |
return { | |
get: function (make, model, processor) { | |
if (!flyweights[make + model]) { | |
flyweights[make + model] = | |
new Flyweight(make, model, processor); | |
} | |
return flyweights[make + model]; | |
}, | |
getCount: function () { | |
var count = 0; | |
for (var f in flyweights) count++; | |
return count; | |
} | |
} | |
})(); | |
function ComputerCollection () { | |
var computers = {}; | |
var count = 0; | |
return { | |
add: function (make, model, processor, memory, tag) { | |
computers[tag] = | |
new Computer(make, model, processor, memory, tag); | |
count++; | |
}, | |
get: function (tag) { | |
return computers[tag]; | |
}, | |
getCount: function () { | |
return count; | |
} | |
}; | |
} | |
var Computer = function (make, model, processor, memory, tag) { | |
this.flyweight = FlyWeightFactory.get(make, model, processor); | |
this.memory = memory; | |
this.tag = tag; | |
this.getMake = function () { | |
return this.flyweight.make; | |
} | |
// ... | |
} | |
// log helper | |
var log = (function () { | |
var log = ""; | |
return { | |
add: function (msg) { log += msg + "\n"; }, | |
show: function () { alert(log); log = ""; } | |
} | |
})(); | |
function run() { | |
var computers = new ComputerCollection(); | |
computers.add("Dell", "Studio XPS", "Intel", "5G", "Y755P"); | |
computers.add("Dell", "Studio XPS", "Intel", "6G", "X997T"); | |
computers.add("Dell", "Studio XPS", "Intel", "2G", "U8U80"); | |
computers.add("Dell", "Studio XPS", "Intel", "2G", "NT777"); | |
computers.add("Dell", "Studio XPS", "Intel", "2G", "0J88A"); | |
computers.add("HP", "Envy", "Intel", "4G", "CNU883701"); | |
computers.add("HP", "Envy", "Intel", "2G", "TXU003283"); | |
log.add("Computers: " + computers.getCount()); | |
log.add("Flyweights: " + FlyWeightFactory.getCount()); | |
log.show(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment