-->

如何正确销毁类(How to properly destroy a class)

2019-09-22 17:52发布

在Ruby,我有一个DAO类,它是由一类使得管理更容易的连接,这是由表示和在DB中,这是由另一类进一步扩展操纵数据的类扩展延长。 要使用动物比喻它是这样的:

class Animal
 ...
end

class Mammal < Animal
 ...
end

class Feline < Mammal
 ...
end

class Cat < Feline
 ...
end

class Lion < Cat
 ...
end

...

在PHP中,有__destruct ,当你破坏/删除类运行方法。 而应该是类扩展另一个类,只需添加parent::__destruct()到类的__destruct这样的方法:

public function __destruct() {
  // Clean up code for this class here
  ...

  // Execute clean up code for Parent class
  parent::__destruct();
}

我可能对除所有类相似的方法Animal 。 因为它不延长的话,就是parent::__destruct(); 线不再有效。

不过,据我所知,Ruby没有像这样的对象的方法。 终结器可设定,但我决定只是把一个cleanup方法我可以调用每当我要毁掉/删除一个类。 这将采取任何必要的类我的设置之前做保健nil

这虽然提出了一个新的问题。 如果方法总是被命名为cleanup和我打电话lion_instance.cleanup ,我认为它会调用Lion#cleanup 。 那么,如何得到它来调用cleanupCat ,然后Feline和环比下跌?

或者这是一种错误的做法,你有更好的想法?

Answer 1:

Ruby的成语,这是屈服于它不工作的模块,并且当块的回报,做清理。 Ruby的内置“File.open”做到这一点:

File.open("/tmp/foo") do |file|
  file.puts "foo"
end

当块结束时,文件被关闭了你,没有你做任何事情。 这是一个很好的习惯用法。 这里是你将如何实现这样的事情:

class Foo

  def self.open(*args)
     foo = new(*args)
     yield foo
     foo.close
  end

  def initialize
    # do setup here
  end

  def close
    # do teardown here
  end

end

并使用它:

Foo.open do |foo|
  # use foo
end

Foo#close自动将后引起的end


这将与子类正常工作。 这是因为类方法继承,就像是实例方法。 这里的超类:

class Superclass

  def self.open(*args)
    o = new(*args)
    yield o
    o.close
  end

  def initialize
    # common setup behavior
  end

  def close
    # common cleanup behavior
  end

end

和两个派生类:

class Foo < Superclass

  def initialize
    super
    # do subclass specific setup here
  end

  def close
    super
    # do subclass specific teardown here
  end

end

class Bar < Superclass

  def initialize
    super
    # do subclass specific setup here
  end

  def close
    super
    # do subclass specific teardown here
  end

end

使用方法:

Foo.open do |foo|
  # use foo
end

Bar.open do |bar|
  # use bar
end

如果你真的需要确保清理发生的无论是什么,然后使用确保在类方法子句:

  def self.open(*args)
     foo = new(*args)
     begin
       yield foo
     ensure
       foo.close
     end
  end

这样一来,清理情况即使在块异常。



Answer 2:

您可以使用ObjectSpace.define_finalizer

就像是:

class Animal
  def initialize
    ObjectSpace.define_finalizer(self, proc { # your code })
   end
end


Answer 3:

好了,因为没有人回答你的问题有关该方法的移动它的方式继承链...

class Cat
  def rawr
    puts "rawr"
  end
end

class Kitty < Cat
  def rawr
    puts "meow"
    super
  end
end

Cat.new.rawr
"Rawr"

Kitty.new.rawr
"rawr"
"meow"

在一个方法,你可以通过调用超级访问父类的同名方法。



文章来源: How to properly destroy a class