开发者

Which is the best/most used singleton coding convention in Ruby?

In the Ruby Standard Library we have the Singleton class:

http://ruby-doc.org/stdlib/libdoc/singleton/rdoc/index.html

We can make any class a singleton by including this class inside. I just rarely see this used. When would it make sense to use this Singleton class vs. just using plain old class methods - also known as singleton methods开发者_如何学编程?

Said in another way: Which Singleton coding-convention are the best and why? Here are three ways I could think of:

require 'singleton'
class Foo
  include Singleton
  # method definitions go here...
end

Foo.instance.do_something!

Versus

class Foo
  class << self
    # method definitions go here...
  end
end

Foo.do_something!

Versus

module Foo
  class << self
    # method definitions go here...
  end
end

Foo.do_something!


WARNING: Opinions ahead!


If you just need a single object, just use a single object:

class << (Foo = Object.new)
  # method definitions go here...
end

Foo.do_something!

Modules are for sharing behavior between objects. Classes are factories for objects. Note the plural: if you have only one object, you need neither a facility for sharing behavior nor a factory for producing multiple copies.

Whether or not this is considered idiomatic Ruby depends largely on which "Ruby" you are talking about: are you talking about Ruby as used by Rails programmers, Ruby as used by Smalltalk programmers, Ruby as used by Java programmers or Ruby as used by Ruby programmers? There are significant differences in the styles used by these different communities.

For example, old time Rubyists like David Alan Black tend to start always with just objects and singleton methods. Only if they later on discover duplicated behavior between objects will they extract that behavior into a mixin and extend the objects with it. (Note that at this stage, there still aren't any classes!)

Classes are created, again, only by refactoring, not by upfront design, when and only when there is duplicated structure between objects.


The most common approach I've seen is neither a singleton nor a class that you never instantiate. The most common and idiomatic way to do this is a module.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜