Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactors the code in the singlton design pattern #66

Merged
merged 1 commit into from Feb 28, 2013
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
96 changes: 56 additions & 40 deletions chapters/design_patterns/singleton.md
Expand Up @@ -7,59 +7,75 @@ chapter: Design Patterns


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. 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.



## Solution ## Solution


The publicly 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. The publicly 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.


The actual definition of the singleton class follows. This is works because CoffeeScript allows you to define executable statements inside a class definition. However, because most CoffeeScript compiles into a [IIFE][] wrapper you do not have to place the private class inside the class definition if this style suits you. The later might be useful when developing modular code such as found in [CommonJS][] (Node.js) or [Require.js][] (See the discussion for an example).


Note that I am using the idiomatic module export feature to emphasize the publicly accessible portion of the module. Remember coffeescript wraps all files in a function block to protect the global namespace. [IIFE]: http://benalman.com/news/2010/11/immediately-invoked-function-expression/
[CommonJS]: http://www.commonjs.org/
[Require.js]: http://requirejs.org/


{% highlight coffeescript %} {% highlight coffeescript %}
root = exports ? this # http://stackoverflow.com/questions/4214731/coffeescript-global-variables class Singleton

# You can add statements inside the class definition
# The publicly accessible Singleton fetcher # which helps establish private scope (due to closures)
class root.Singleton # instance is defined as null to force correct scope
_instance = undefined # Must be declared here to force the closure on the class instance = null
@get: (args) -> # Must be a static method # Create a private class that we can initialize however
_instance ?= new _Singleton args # defined inside this scope to force the use of the

# singleton class.
# The actual Singleton class class PrivateClass
class _Singleton constructor: (@message) ->
constructor: (@args) -> echo: -> @message

# This is a static method used to either retrieve the
echo: -> # instance or create a new one.
@args @get: (message) ->

instance ?= new PrivateClass(message)
a = root.Singleton.get 'Hello A'
a.echo() a = Singleton.get "Hello A"
# => 'Hello A' a.echo() # => "Hello A"


b = root.Singleton.get 'Hello B' b = Singleton.get "Hello B"
a.echo() b.echo() # => "Hello A"
# => 'Hello A'
Singleton.instance # => undefined
a.instance # => undefined
Singleton.PrivateClass # => undefined
{% endhighlight %}


b.echo()
# => 'Hello A'


root.Singleton._instance ## Discussion
# => undefined


root.Singleton._instance = 'foo' See in the above example how all instances are outputting from the same instance of the Singleton class. You can also see that the PrivateClass and instance variable are not accessible outside the Singleton class. In essance the Singleton class provides a static method get which returns only one instance of PrivateClass and only one. It also hides the PrivateClass from the world so that you can not create your own.


root.Singleton._instance The idea of hiding or making private the inner workings is preference. Especially since by default CoffeeScript wraps the compiled code inside it's own IIFE (closure) allowing you to define classes without worry that it might be accessible from outside the file. In this example, note that I am using the idiomatic module export feature to emphasize the publicly accessible portion of the module. (See this discussion for further explanation on [exporting to the global namespace][1]).
# => 'foo'


c = root.Singleton.get 'Hello C' [1]: http://stackoverflow.com/questions/4214731/coffeescript-global-variables
c.foo()
# => 'Hello A'


a.foo() {% highlight coffeescript %}
# => 'Hello A' root = exports ? this

# Create a private class that we can initialize however
# defined inside the wrapper scope.
class ProtectedClass
constructor: (@message) ->
echo: -> @message

class Singleton
# You can add statements inside the class definition
# which helps establish private scope (due to closures)
# instance is defined as null to force correct scope
instance = null
# This is a static method used to either retrieve the
# instance or create a new one.
@get: (message) ->
instance ?= new ProtectedClass(message)

# Export Singleton as a module
root.Singleton = Singleton
{% endhighlight %} {% endhighlight %}


## Discussion

See in the above example how all instances are outputting from the same instance of the Singleton class.

Note how incredibly simple coffeescript makes this design pattern. For reference and discussion on nice javascript implementations, check out [Essential JavaScript Design Patterns For Beginners](http://addyosmani.com/resources/essentialjsdesignpatterns/book/). Note how incredibly simple coffeescript makes this design pattern. For reference and discussion on nice javascript implementations, check out [Essential JavaScript Design Patterns For Beginners](http://addyosmani.com/resources/essentialjsdesignpatterns/book/).