将类方法委托给Ruby中的对象 [英] Delegating class methods to an object in ruby

查看:92
本文介绍了将类方法委托给Ruby中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将对单例的调用包装在一个类中(因为我不希望其余代码知道它们正在与单例进行对话),所以我查看了委托模块。

I am trying to wrap calls to a singleton in a class (because I do not want the rest of the code to know that they are talking to a singleton), and I looked at the delegate module.

在我的代码中,我有这样的东西:

In my code, I have something like this:

class HideSingleton
  @@obj = SingletonClass.instance # x is an instance of SingletonClass
  # I want to be able to say HideSingleton.blah,
  # where 'blah' is instance method of SingletonClass instance (i.e., 'x')
  SimpleDelegator.new @@obj.field
end

class SingletonClass < BaseClass
  attr_reader :field
  def initialize
    @field = SimpleDelegator.new super(BaseClass Constructor params)
  end
end

然后在irb中:

> require 'singleton_class'
> x = SingletonClass.new
> x.blah  # 'blah' is a method that is present in BaseClass instance
> require 'hide_singleton'
> y = HideSingleton

我该怎么做 y.blah

推荐答案

我认为您尝试执行的操作比较简单,但是可以完成隐藏的单例类委托一个单例类,您可以执行以下操作:

I think there is a simpler implementation of what you are trying to do, but to accomplish the hidden singleton class that delegates to a singleton class, you can do the following:

require 'delegate'
require 'forwardable'

class BaseClass
  def blah
    puts 'hi'
  end
end

class SingletonClass < BaseClass
  attr_reader :field
  def initialize
    @field = SimpleDelegator.new(BaseClass.new)
  end
end

class HideSingleton
  def self.obj
    @@obj ||= SingletonClass.new.field
  end

  def self.method_missing *args
    obj.send *args
  end
end

然后您可以拨打以下电话:

You can then make the following calls:

x = SingletonClass.new
x.blah
hi
=> nil
HideSingleton.blah
hi
=> nil

这篇关于将类方法委托给Ruby中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆