Skip to content

Commit 09ec01d

Browse files
committed
Merge pull request coffeescript-cookbook#22 from emorikawa/master
Added Singleton Pattern
2 parents 56981a6 + 762f543 commit 09ec01d

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
---
2+
layout: recipe
3+
title: Singleton Pattern
4+
chapter: Design Patterns
5+
---
6+
7+
h2. Problem
8+
9+
Many times you only want one, and only one, instance of a class. For example, you may only need one class that creates server resources and you want to ensure that the one object can control those resources. Beware, however, because the singleton pattern can be easily abused to mimic unwanted global variables.
10+
11+
h2. Solution
12+
13+
The publically available class only contains the method to get the one true instance. The instance is kept within the closure of that public object and is always returned
14+
15+
The actual definition of the singleton class follows.
16+
17+
Note that I am using the idiomatic module export feature to emphasize the publically accessible portion of the module. Remember coffeescript wraps all files in a function block to protect the global namespace
18+
19+
{% highlight coffeescript %}
20+
root = exports ? this # http://stackoverflow.com/questions/4214731/coffeescript-global-variables
21+
22+
# The publically accessible Singleton fetcher
23+
class root.Singleton
24+
_instance = undefined # Must be declared here to force the closure on the class
25+
@get: (args) -> # Must be a static method
26+
_instance ?= new _Singleton args
27+
28+
# The actual Singleton class
29+
class _Singleton
30+
constructor: (@args) ->
31+
32+
echo: ->
33+
@args
34+
35+
a = root.Singleton.get 'Hello A'
36+
a.echo()
37+
# => 'Hello A'
38+
39+
b = root.Singleton.get 'Hello B'
40+
a.echo()
41+
# => 'Hello A'
42+
43+
b.echo()
44+
# => 'Hello A'
45+
46+
root.Singleton._instance
47+
# => undefined
48+
49+
root.Singleton._instance = 'foo'
50+
51+
root.Singleton._instance
52+
# => 'foo'
53+
54+
c = root.Singleton.get 'Hello C'
55+
c.foo()
56+
# => 'Hello A'
57+
58+
a.foo()
59+
# => 'Hello A'
60+
{% endhighlight %}
61+
62+
h2. Discussion
63+
64+
See in the above example how all instances are outputting from the same instance of the Singleton class
65+
66+
Note how incredibly simple coffeescript makes this design pattern. For reference and discussion on nice javascript implementations, check out http://addyosmani.com/resources/essentialjsdesignpatterns/book/

0 commit comments

Comments
 (0)