Singleton vs. Monostate Models in Ruby

Suppose a class needs to load an external library, which takes some time to load, and therefore needs to be loaded only once. Two natural solutions for this would be to use a singleton or monostat template. Is there any advantage to any 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 Singleton in Ruby?

+8
oop ruby design-patterns singleton
source share
1 answer

The syntax pattern structurally provides 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 singleton.

Monostat applies behavior of a singleton without the structure of the monostate .

You may find situations where you still need instance data. Therefore, the monostat will be better. You can create an instance, use methods to influence instance data, and still have access to static data. With singleton, you cannot have instance data.

In addition, if you plan to derive classes from singleton, and you want these classes to be single, your best bet is a monostat. This is because all classes derived from a monostat are monostatic. Classes based on singleton classes are not single by default. You will need to add a static method and attribute to each derived class.

+4
source share

All Articles