Created
April 2, 2009 18:24
-
-
Save cassiomarques/89337 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# O problema é que você quer algo que foge do comoportamento esperado em um esquema orientado a objetos. | |
# Se cachorro herda de animal, então cachorro É um animal. Logo, quando cria-se um novo cachorro, a contagem de | |
# animais também deve aumentar. Para burlar esse comportamento fiz o esquema abaixo, usando metaprogramação. | |
class Animal | |
def initialize | |
increment_total | |
end | |
def self.total | |
@@total | |
end | |
def increment_total | |
@@total += 1 rescue @@total = 1 | |
end | |
def self.inherited(klass) | |
klass.class_eval <<-CODE | |
@@#{klass}_total = 0 | |
def increment_total | |
@@#{klass}_total += 1 | |
@@total += 1 | |
end | |
def #{klass}.total; @@#{klass}_total; end | |
CODE | |
end | |
end | |
class Gato < Animal; end | |
class Cachorro < Animal; end | |
class Siames < Gato; end | |
a1 = Animal.new | |
g1 = Gato.new | |
puts "Total de gatos = #{Gato.total}" | |
c1 = Cachorro.new | |
puts "Total de cachorros = #{Cachorro.total}" | |
g2 = Gato.new | |
puts "Total de gatos = #{Gato.total}" | |
c2 = Cachorro.new | |
puts "Total de cachorros = #{Cachorro.total}" | |
c3 = Cachorro.new | |
puts "Total de cachorros = #{Cachorro.total}" | |
puts "Total de gatos = #{Gato.total}" | |
puts "Total de animais = #{Animal.total}" | |
puts "Total de siameses = #{Siames.total}" | |
s = Siames.new | |
puts "Total de siameses = #{Siames.total}" | |
puts "Total de animais = #{Animal.total}" | |
puts "Total de gatos = #{Gato.total}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment