我正在设法找到一种方法来安全地释放一个类获得的资源。我试过使用finalize,但它不可靠。有时,在GC有机会释放资源之前,我会关闭我的程序。
因此,我决定在这样的块中使用类实例:
class Foo
def destroy # free resources
#...
end
#...
def self.create(*args)
instance = self.new(*args)
begin
yield instance
ensure
instance.destroy
end
end
Foo.create do |foo|
# use foo
end这很好,但我仍然可以使用new创建一个必须显式destroy的实例。我试图编写自己的new,但在默认情况下,它似乎只是重载了new。
是否有办法重新定义\禁用new
发布于 2018-05-14 06:33:43
那就是initialize方法,应该是private
class Foo
@foo : String
private def initialize(@foo)
end
def destroy
puts "Destroying #{self}"
end
def self.create(arg)
instance = new(arg)
yield instance
ensure
instance.destroy if instance
end
end
Foo.create("bar") do |foo| # will work
p foo
end
Foo.new("bar") # will raisehttps://stackoverflow.com/questions/50314022
复制相似问题