Singleton vs. Monostate Pattern in Ruby
Asked Answered
S

1

7

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?

Sequel answered 2/1, 2012 at 7:0 Comment(2)
The require method loads a library and prevents it from being loaded more than once.Maelstrom
I was referring specifically to a non-Ruby library, which cannot be handled simply by require, although your suggestion would point to a third way of achieving the same thing: class 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
B
4

The singleton pattern structurally enforces the fact that you can never have more than one instance of a class at a time, and it is obvious to the developers that they are dealing with a singleton.

The monostate enforces the behavior of a singleton without the structure of the monostate.

You might find situations where you still need instance data. Therefore a monostate would be better. You can create the instance, use methods to affect instance data and still have access to the static data. With a singleton, you cannot have instance data.

Besides, If you plan on deriving classes from the singleton and you want those classes to be singletons, your better choice is monostate. That’s because all classes derived from a monostate are monostates. Classes derived singleton classes are not singletons by default. You would have to add the static method and attribute to each derived class.

Boreas answered 2/1, 2012 at 7:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.