Ruby类和实例变量跨继承生命周期演示

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Ruby类和实例变量跨继承生命周期演示相关的知识,希望对你有一定的参考价值。

  1. require 'logger'
  2. $log = Logger.new(STDOUT)
  3. $log.level = Logger::INFO
  4. $log.progname = "LifecycleDemo"
  5. $log.formatter = proc { |severity, datetime, progname, msg|
  6. #"#{datetime.strftime("%Y-%b-%d %a %H:%M")} #{severity} #{progname} {#{msg}} "
  7. "#{msg} "
  8. }
  9. #$log.datetime_format = "%a %Y-%m-%d %H:%M"
  10.  
  11.  
  12. class FirstClass
  13. @@grandClass = "FirstClassVar" # class level variable to track
  14. def initialize
  15. @grandVar = "FirstInstanceVar" # instance variable to track
  16. $log.info("! FirstClass init, #{ids}")
  17. end
  18. def grand
  19. $log.info("> FirstClass grand, #{ids}")
  20. end
  21.  
  22. def ids
  23. "#{self.class.name}:: #{@@grandClass}:#{@@grandClass.object_id}, #{@grandVar}:#{@grandVar.object_id}"
  24. end
  25. end
  26.  
  27. class SecondClass < FirstClass
  28. def initialize
  29. @ego_hilite = "-" * 15
  30. super
  31. $log.info("! Second class init, #{ids}")
  32. end
  33. def spill_it
  34. $log.info("> Spill It call, #{ids}")
  35. end
  36. def alter_ego
  37. @grandVar = "SecondInstanceVar"
  38. @@grandClass = "SecondClassVar"
  39. $log.info(" #{@ego_hilite} Ego altered by the #{self.class.name} #{@ego_hilite} ")
  40. end
  41. end
  42.  
  43. class ThirdClass < SecondClass
  44. @@grandClass = "ThirdClassStatic"
  45. def initialize
  46. super
  47. $log.info("! 3rd class init, #{ids}")
  48. end
  49. def alter_ego
  50. @grandVar = "ThirdInstanceVar"
  51. @@grandClass = "ThirdClassVar"
  52. $log.info(" #{@ego_hilite} Ego altered by the Third Class #{@ego_hilite} ")
  53. end
  54. end
  55.  
  56. def test(instance)
  57. hilite = "*" * 20
  58. $log.info(" #{hilite} Testing instance of #{instance.class.name} BEGIN #{hilite}")
  59. instance.grand
  60. instance.spill_it
  61.  
  62. # see what gets changed if anything:
  63. instance.alter_ego
  64.  
  65. instance.grand
  66. instance.spill_it
  67. $log.info(" #{hilite} Testing instance of #{instance.class.name} END #{hilite}")
  68. end
  69.  
  70. test(SecondClass.new)
  71. test(ThirdClass.new)

以上是关于Ruby类和实例变量跨继承生命周期演示的主要内容,如果未能解决你的问题,请参考以下文章

继承Thread类和实现Runnable接口创建的线程对于实例变量和类变量的共享

Ruby类实例变量和继承

ruby中的实例变量和类变量

c++类中 各种成员的生命周期?

依赖注入生命周期

java 静态变量生命周期(类生命周期)