Advertisement
Guest User

Untitled

a guest
Jun 19th, 2019
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.79 KB | None | 0 0
  1. # Flyweight
  2. class BigChar
  3. def initialize(char)
  4. @big_char = "#{char} expended a lot of memory"
  5. end
  6.  
  7. def to_s
  8. "#{@big_char}"
  9. end
  10. end
  11.  
  12. # FlyweightFactory
  13. class BigCharFactory
  14. def initialize
  15. @pool = {}
  16. end
  17.  
  18. # singleton
  19. @singleton = new
  20. class << self
  21. def get_instance
  22. @singleton
  23. end
  24. end
  25. private_class_method :new
  26.  
  27. def get_big_char(char)
  28. return @pool[char] if @pool.key?(char)
  29.  
  30. @pool[char] = BigChar.new(char)
  31. @pool[char]
  32. end
  33. end
  34.  
  35. # Client
  36. class BigString
  37. def initialize(string)
  38. @big_chars = []
  39. @big_char_factory = BigCharFactory.get_instance
  40. string.each_char {|c| @big_chars << @big_char_factory.get_big_char(c) }
  41. end
  42.  
  43. def print
  44. @big_chars.each {|bc| puts(bc) }
  45. end
  46. end
  47.  
  48. # main
  49. big_string = BigString.new('12345')
  50. big_string.print
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement