Singleton Pattern is a design pattern that allow a class to be instantiated only once. The benefit of Singleton is to be ensure that there is only one and the same instance of object is called every time. Ruby also support Singleton Pattern.
In order to create a singleton class in Ruby, Singleton
module needs to be included.
Check out the code below:
1 2 3 4 5 6 7 8 9 10 11 |
|
The example above created a ruby singleton class called OpensrsServer
, with an instance method called connection
. This class is responsible for creating a connection object using OpenSRS
gem.
In order to instantiate an object with singleton class in Ruby, we need to use .instance
method rather than .new
.
1
|
|
No matter how many time OpenSRSServer.instance
get called, the object returned will be the same.