mardi 19 janvier 2016

use Ruby Singleton pattern to implement Logging

thanks for your time!

I read this article about Ruby Singleton Pattern. This is a code snippet from it, which used Singleton Pattern to fulfill a Logger class.

class Logger
  def initialize
    @log = File.open("log.txt", "a")
  end

  @@instance = Logger.new

  def self.instance
    return @@instance
  end

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

  private_class_method :new
end

Logger.instance.log("message 1")

But I cannot digest these codes. Why it have to be this way. What's the benefits compared with following codes.

class Logger
  @@instance = File.open("log.txt", "a")

  def self.log(msg)
    @@instance.puts(msg)
  end
end

Logger.log("message 2")

Aucun commentaire:

Enregistrer un commentaire