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?