Guest User

Untitled

a guest
May 26th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. ##
  2. # This files shows some possible implementations of the Singleton pattern
  3. # in Ruby. I'm not a huge fan of the Singleton pattern, but it's nice
  4. # in some cases. In this file I'm going to implement a simple logger.
  5. #
  6.  
  7.  
  8. ##
  9. # The first implementation that can come to our minds is to create a class
  10. # that holds an instance as a class variable that can be accessed through
  11. # the instance method called 'instance'. Then, with this instance you can
  12. # log as usual. Furthermore, the 'new' class method is kept private to prevent
  13. # the programmer of instantiating new logs.
  14. class Log
  15. def initialize
  16. @log = File.new 'log.txt', 'a'
  17. end
  18.  
  19. def log(msg)
  20. @log.puts msg
  21. end
  22.  
  23. @@instance = Log.new
  24.  
  25. def instance
  26. @@instance
  27. end
  28.  
  29. private_class_method :new
  30. end
  31.  
  32.  
  33. ##
  34. # We can also achieve the above implementation by including the
  35. # Singleton module.
  36.  
  37. require 'singleton'
  38.  
  39. class IncludedSingletonLog
  40. include Singleton
  41.  
  42. def initialize
  43. @log = File.new 'log.txt', 'a'
  44. end
  45.  
  46. def log(msg)
  47. @log.puts msg
  48. end
  49. end
  50.  
  51.  
  52. ##
  53. # And here is a more basic implementation. Here I want to show the idea of
  54. # eager instantiation (which also applies to the techniques used above).
  55. # Eager instantiation means that the instance is created when the class gets
  56. # loaded, even if it's not used.
  57. class EagerLog
  58. @@log = File.new 'log.txt', 'a'
  59.  
  60. def self.log(msg)
  61. @@log.puts msg
  62. end
  63.  
  64. private_class_method :new
  65. end
  66.  
  67.  
  68. ##
  69. # On the other hand, lazy instantiation means that the instance is created
  70. # only when the programmer wants to use this class for the first time.
  71. class LazyLog
  72. def self.log
  73. @@log ||= File.new 'log.txt', 'a'
  74. @@log.puts msg
  75. end
  76.  
  77. private_class_method :new
  78. end
  79.  
  80.  
  81. ##
  82. # In Ruby, the difference between a Module and a Class is just three methods:
  83. # :new, :allocate and :superclass. So a Module is almost the same as a Class
  84. # but it cannot be instantiated. Cool, we now can implement the above classes
  85. # as modules but without calling the private_class_method method.
  86. module ModuleLog
  87. @@log = File.new 'log.txt', 'a'
  88.  
  89. def self.log(msg)
  90. @@log.puts msg
  91. end
  92. end
Add Comment
Please, Sign In to add comment