Suppose a class needs to load an external library which takes some time to load and thus should be loaded only once. Two natural solutions to this would be to use the singleton pattern or the monostate pattern. Is there any advantage to either of these solutions in this particular context in Ruby?
For example:
# Using a Singleton class
require 'singleton'
class Parser
include Singleton
def initialize
@parser = load_external_library
end
def parse(sentence)
@parser.parse(sentence)
end
end
# Then calling using...
Parser.instance.parse(sentence)
Versus:
# Using a Monostate class
class Parser
def self.parse(sentence)
@@parser ||= load_external_library
@@parser.parse(sentence)
end
end
# Then calling using...
Parser.parse(sentence)
Since the second syntax is much cleaner, are there any advantages to using the Singleton in Ruby?
require
method loads a library and prevents it from being loaded more than once. – Maelstromclass Parser; @@parser = load_external_library; def self.parse(sentence); @@parser.parse(sentence); end; end
... then in another file,require 'parser'
. This seems similar to the monostate, but the user code is now responsible for requiring it only once, which can be trickier than expected. Any thoughts? – Sequel