coffee-factory

Javascript class Factory generator implemented in Coffeescript.

Coffee Factory

Javascript class Factory generator implemented in Coffeescript.

npm install --save coffee-factory
  • klass The class to instantiate when Factory#get() called
  • maxReuse The maximum number of existing instance to keep at any one time. FIFO.
  • ctorArgs Arguments passed to constructor when new instantiations created
  • initArgs Arguments passed to .initialize() of instance when Factory#get() called
  • obj An instance to give the Factory for re-use
Factory = require 'coffee-factory'
 
class User
  name: "default"
  initialize: ->
    @name = ""
 
UserFactory = new Factory User10 # Create the factory 
 
# Get an instance. 
# No instances are stored in the factory, so a new one is created 
user = UserFactory.get()
console.log user.name # Output: "" - because `.initialize()` is called 
 
user.name = "Foo"
 
# We no longer want this instance, so let the factory reuse it 
UserFactory.put user
user = null
# Normally, garbage collection would delete the object form memory 
 
# Get another instance. There is one stored, so that will be used. 
# Before returning, `.initialize` (if it exists) will be called on the instance 
user2 = UserFactory.get()
console.log user.name # Output: "" 
Factory = require 'coffee-factory'
 
class User
  name: "default"
  initialize: (@name = "") ->
 
UserFactory = new Factory User10 # Create the factory 
 
user = UserFactory.get "Foo"
console.log user.name # Output: "Foo" - the param was passed to `.initialize()` 
Factory = require 'coffee-factory'
 
class User
  name: "default"
  constructor: (@name = "") ->
 
# The "Foo" parameter will be passed to the constructor of User when `.get()` is called 
UserFactory = new Factory User10"Foo"
 
user = UserFactory.get()
console.log user.name # Output: "Foo" 
 
user2 = UserFactory.get()
console.log user2.name # Output: "Foo" 
Factory = require 'coffee-factory'
 
class User
  isStaff: false
  constructor: (@isStaff) ->
 
# The "Foo" parameter will be passed to the constructor of User when `.get()` is called 
StaffUser = new Factory User10true
 
ceo = StaffUser.get()
console.log ceo.isStaff # Output: true 

Like what I've created? So do I! I develop this project in my spare time, free for the community.

If you'd like to say thanks, buy me a beer by tipping with Dogecoin: DJLZccHAcz19ikSV1D5jY3WdFPU7Nqjmfk