ALo*_*LoR 3 ruby singleton metaprogramming
我想调用Singleton对象的方法而不引用它的实例
SingletonKlass.my_method
Run Code Online (Sandbox Code Playgroud)
代替
SingletonKlass.instance.my_method
Run Code Online (Sandbox Code Playgroud)
我想出了这个解决方案(在课堂上使用method_missing):
require 'singleton'
class SingletonKlass
include Singleton
def self.method_missing(method, *args, &block)
self.instance.send(method, *args)
end
def my_method
puts "hi there!!"
end
end
Run Code Online (Sandbox Code Playgroud)
这有什么缺点吗?还有更好的解决方案吗?你的任何推荐?
谢谢.
更新:
我的目标是将一个模块与单例类混合:
module NoInstanceSingleton
def method_missing(method, *args)
self.instance.send(method, *args)
end
end
Run Code Online (Sandbox Code Playgroud)
结束然后在课堂上使用它:
class SingletonKlass
include Singleton
extend NoInstanceSingleton
def method1; end
def method2; end
...
def methodN; end
end
Run Code Online (Sandbox Code Playgroud)
我想能够直接打电话:
SingletonKlass.method1
Run Code Online (Sandbox Code Playgroud)
And*_*imm 12
使用forwardable和def_delegators:
require 'singleton'
require 'forwardable'
class SingletonKlass
include Singleton
class << self
extend Forwardable
def_delegators :instance, :my_method
end
def my_method
puts "hi there!!"
end
end
SingletonKlass.my_method
Run Code Online (Sandbox Code Playgroud)
编辑:如果你想包括你自己定义的所有方法,你可以做到
require 'singleton'
require 'forwardable'
class SingletonKlass
include Singleton
def my_method
puts "hi there!!"
end
class << self
extend Forwardable
def_delegators :instance, *SingletonKlass.instance_methods(false)
end
end
SingletonKlass.my_method
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2432 次 |
| 最近记录: |