Skip to content

Instantly share code, notes, and snippets.

@chischaschos
Created August 16, 2010 17:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chischaschos/527366 to your computer and use it in GitHub Desktop.
Save chischaschos/527366 to your computer and use it in GitHub Desktop.
#Refactor following code using singleton pattern and explain your answer
require 'singleton'
class Logger
include Singleton
LOG_FILE_NAME = 'dev.log'
def initialize
@file = File.exists?('dev.log') ? File.open('dev.log', 'a') : File.new('dev.log', 'a')
end
def <<(msg)
@file << msg
end
end
class SM1
def initialize
Logger.instance << 'Just creating ' + self.class.to_s + "\n"
end
end
class SM2
def initialize
Logger.instance << 'Just creating ' + self.class.to_s + "\n"
end
def say_hi
puts 'Hi somebody'
Logger.instance << "Just said hi\n"
end
end
class SM3
def to_str
msg = "I'm a #{self.class.to_s} hell yeah"
Logger.instance << msg
msg
end
end
# Usage test
sm1 = SM1.new
sm2 = SM2.new
sm2.say_hi
sm3 = SM3.new
p sm3.to_str
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment