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?
A Singleton class can Dispose, while a static class can not. A Singleton class can have a constructor, while a static class can only have a private static parameterless constructor and cannot have instance constructors. A Static class has better performance since static methods are bonded on compile time.
A Singleton can implement interfaces, inherit from other classes and allow inheritance. While a static class cannot inherit their instance members. So Singleton is more flexible than static classes and can maintain state.
Singleton is a creational design pattern, which ensures that only one object of its kind exists and provides a single point of access to it for any other code. Singleton has almost the same pros and cons as global variables. Although they're super-handy, they break the modularity of your code.
The Singleton Ruby mixin itself is thread safe. It means that you are guaranteed to get the same instance in all threads, and only that! It doesn't mean that methods which you implement for a singleton class by yourself will be thread safe.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With