I have the following piece of code:
class Fish
# @message = "I can swim"
class << self
@message = "I can jump!"
define_method(:action) { @message }
end
end
Fish.action => nil
As soon as I uncomment the above @message
variable, Fish.action
returns I can swim
. Why in both cases it is ignoring the I can jump
message. Why is that? Why is Fish class being binded to the @message
defined at the start but not inside the singleton
class?
The purpose of Singleton is to have only one instance of that object[1]. By making a sealed class with a private static instance which is automatically instantiated on first access, you provide its necessary trait of only creating one copy of the actual object that is then accessed by the Singleton.
Definitely the most common usage is that singleton is normal object that holds member variables. You can, for example, easily replace one object with another (with all other properties). Every class can have static variables but it does not deppend wheter it is singleton or not.
Well-designed singleton can have only one instance per application. Creating of multiple instances is a mistake in the application design.
A singleton is a class that allows only a single instance of itself to be created and gives access to that created instance. It contains static variables that can accommodate unique and private instances of itself. It is used in scenarios when a user wants to restrict instantiation of a class to only one object.
In the main class, we instantiate the singleton class with 3 objects x, y, z by calling static method getInstance(). But actually after creation of object x, variables y and z are pointed to object x as shown in the diagram. Hence, if we change the variables of object x, that is reflected when we access the variables of objects y and z.
If it wasn’t static, the singleton would behave like a factory and keep creating new instances. Because if it wasn’t static you’d be creating a new instance of the class every time you invoked the singleton method on the singleton class. Static ensures there is only one instance of the variable across all instances of the class.
The variables that are declared inside the class but outside the scope of any method are called instance variables in Java. The instance variable is initialized at the time of the class loading or when an object of the class is created.
If we allow only one instance of any class that means we will have a shared object (somewhat how does a class variable or static variable works). This will solve our problem explained in the previous post.
It's because class << self
opens the class' singleton class context:
class Foo
p self # Foo
class << self
p self # #<Class:Foo>
define_method(:bar) { p self } # Foo
end
end
Foo.bar
You can verify that by:
Fish.singleton_class.instance_variable_get(:@action) # => "I can jump!"
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