Singleton Pattern - CoffeeScript Design Patterns

Posted on

Turns out there actually is a good use for the Singleton pattern in Javascript/CoffeeScript: making data available to all AMD modules in a project without the use of globals. I’ve used this to great effect with dynamic configuration data and session data. While there are a few solutions out there (even implemented in Coffee), I’ve found that this one is the closest to the GoF Design Patterns implementation.

[code lang=“coffee”]
class Singleton
@_instance: null
@getInstance: ->
@_instance ||= new @ arguments…
[/code]

Usage:

One could use the Singleton class directly but I like to extend it so that the Singleton class itself stays reusable.

[code lang=“coffee”]
class Registry extends Singleton
constructor: ->
properties: {}
set: (key, val) ->
@properties[key] = val
return
get: (key) ->
@properties[key]

registry = Registry.getInstance()
registry.set "ohai", "there"
console.log registry.get "ohai"
[/code]