addyosmani / essential-js-design-patterns

Repo for my 'Learning JavaScript Design Patterns' book
http://addyosmani.com/resources/essentialjsdesignpatterns/book/
4.83k stars 792 forks source link

Flyweight issue #74

Closed addyosmani closed 11 years ago

addyosmani commented 11 years ago

Hi

I'm reading your book "Learning JavaScript Design Patterns" and I found an error in the code example for the flyweight pattern.

The CoffeFlavorFactory is not working properly because "var flavor = falvors[flavorName];" is always undefined.

Here is a fix proposal:

// FlyweightFactory object function CoffeeFlavorFactory() { var flavors = {}, length = 0;

return { getCoffeeFlavor: function( flavorName ) {

var flavor = flavors[flavorName]; if (flavor === undefined) { flavor = new CoffeeFlavor( flavorName ); flavors[flavorName] = flavor; length++; } return flavor; },

getTotalCoffeeFlavorsMade: function() { return length; } }; }

Your original code instantiate 15 CoffeFlavor objects where this one only instantiate 3, which is what is expected.

Anyway, thank you for this amazing helpful book ;)

Best, Jeremie Patonnier