gpt4 book ai didi

Ruby Singleton 避免使用实例成员

转载 作者:数据小太阳 更新时间:2023-10-29 08:28:17 24 4
gpt4 key购买 nike

我喜欢 Ruby 的单例,但我想更好地使用它,所以这里是示例

require 'singleton'

class Foo
include Singleton

def initialize
# code to setup singleton here
end

def self.get_bar
Foo.instance.get_bar
end

def get_bar
end

def get_nar
end
end

用法

Foo.instance.get_bar(默认)或 Foo.get_bar(由于我制作的静态 self.get_bar 方法)

有没有优雅的方法可以让所有方法都可以访问,而不必为每个方法编写静态包装器?必须为每个方法编写 .instance

似乎是多余的

更新

ruby 1.8.7

最佳答案

你可以混合这个模块:

module DelegateToSingleton

def respond_to_missing?(method)
super || instance.respond_to?(method)
end

def method_missing(method, *args)
instance.send(method, *args)
end

end

进入你的单例:

class Foo

extend DelegateToSingleton
include Singleton

def foo
'foo'
end

def bar
'bar'
end

end

结果如下:

p Foo.foo    # => "foo"
p Foo.bar # => "bar"

DelegateToSingleton::method_missing 是它起作用的原因:每当 Foo 收到一个它不知道的方法时,它只是将它转发给它的实例。

DelegateToSingleton::respond_to_missing? 不是严格需要的,但在使用 method_missing 玩花样时拥有它是一种礼貌。

对于 1.9.2 之前的 Ruby:Override respond_to? instead of respond_to_missing?

关于Ruby Singleton 避免使用实例成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12299598/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com