consider the following two classes:
class Foo1
attr_accessor :data
include Singleton
end
class Foo2
def data
return @@data
end
def data=(val)
@@data = val
end
end
in irb screen:
[mkhan@localhost mkhan]$ irb
irb(main):001:0> require 'singleton'
=> true
irb(main):002:0> class Foo1
irb(main):003:1> attr_accessor :value
irb(main):004:1> include Singleton
irb(main):005:1> end
=> Foo1
irb(main):006:0> a = Foo1.instance
=> #<Foo1:0xf6fc4d4c>
irb(main):007:0> b = Foo1.instance
=> #<Foo1:0xf6fc4d4c>
irb(main):009:0> a.value = 100
=> 100
irb(main):010:0> p b.value
100
=> nil
irb(main):011:0> class Foo2
irb(main):012:1> def value
irb(main):013:2> return @@value
irb(main):014:2> end
irb(main):015:1> def value=(val)
irb(main):016:2> @@value = val
irb(main):017:2> end
irb(main):018:1> end
=> nil
irb(main):019:0> a = Foo2.new
=> #<Foo2:0xf6fe0cb8>
irb(main):020:0> b = Foo2.new
=> #<Foo2:0xf6fdcf00>
irb(main):022:0> a.value = 100
=> 100
irb(main):023:0> p b.value
100
=> nil
in both class we will have single instance of 'data'.
Which one is better and why?
Can someone explain it, please.
Thanks in advance...