Monday, February 26, 2018

Design Patterns - Singleton

Singleton pattern is frequently used to provide global access point for a service. It restricts instantiation of a class to only one instance that globally available.

It's useful in your application when you need global instance which can be accessible in different parts of the application. Most common use case of this pattern is Application logging and configuration functionality.

Singleton pattern in Ruby

Class Logger
def initialize
@log = File.open("/tmp/tmp.log", "a")
end

@@instance = Logger.new

def self.instance
@@instance
end

def log(message)
@log.puts(message)
end

private_method :new
end


Logger.instance.log("Log me")

In this example, we created an instance of the "Class Logger" which can be accessed by class method "Logger.instance", so when you want to log any errors/warning/notice on your app, you can simply use "log" instance method which just opened a log file and appending message on that file. 

 At the end of the class we made method "new" as private, so that anywhere in the application we can't create new instance of Class "Logger"

No comments:

Post a Comment