singleton in ruby

# SINGLETON 
# Not a thread safe solution.
class Factory
    @@instance = nil
    private_class_method :new
    def Factory.get_instance
        @@instance = new unless @instance
        @@instance
    end

public
    def foo
        "foo~"
    end
end

f = Factory.get_instance
puts f.foo

# SINGLETON METHOD
# Each instance gets a method after instantiation.
class Logger

    def initialize(type)
        @type = type
    end

    def log(msg)
        puts msg
    end
end

l1 = Logger.new("screen")
l2 = Logger.new("file")

def l1.clear
    puts "screen cleared"
end

def l2.flush
    puts "buffer flushed"
end

l1.clear
l2.flush

Similar Posts:

Post a Comment

Your email is never published nor shared.