Created
August 16, 2010 17:33
-
-
Save chischaschos/527366 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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