单例模式、私有方法和单例模块

发布于 2024-12-17 17:27:17 字数 431 浏览 1 评论 0原文

我正在与 Ruby 中的单例模式作斗争。

我知道单例实现了对象的单个实例,但我不太明白我们是否可以在没有单例模块的​​情况下复制它。

然后是私有方法的问题;现在我必须做这样的事情:

class MyTestClass
  private_class_method :new
  class << self
    def test
      puts hello
    end

    private
    def hello
      'hello world'
    end
  end
end

MyTestClass.test

所以我的问题是:

  1. 上面是一个好的单例模式吗?
  2. 这能确保只有一个实例吗?
  3. 有没有办法使用单例模块来拥有私有方法?

I am fighting with singleton patterns in Ruby.

I know that singleton implements a single instance of an object but I don't quite understand if we can replicate it without the singleton module.

Then there is the issue with private methods; Right now I have to do something like this:

class MyTestClass
  private_class_method :new
  class << self
    def test
      puts hello
    end

    private
    def hello
      'hello world'
    end
  end
end

MyTestClass.test

So my questions are:

  1. Is the above a good Singleton pattern?
  2. Would this make sure there is only a single instance?
  3. Is there a way to have private methods using the singleton module?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

写给空气的情书 2024-12-24 17:27:17

1.以上是一个好的单例模式

?可能不是。仅使用类方法,您无法获得为单个“实例”执行初始化函数的好处,因此它缺少通常在单例中找到的一些部分。 Ruby 足够灵活,因此您可以根据需要将任何缺失的功能附加到“类”对象上,但它开始看起来有点难看。

2.这能确保只有一个实例吗?

是的。您正在修改代表该类的对象,并且只有一个对象。

3.有没有办法使用单例模块来拥有私有方法?

是的。你尝试过吗?正如您所期望的那样。

class Test
  include Singleton
  def public_test
    "foo"
  end
  private
  def private_test
    "bar"
  end
end

Test.instance.public_test  # => "foo"
Test.instance.private_test # => throws exception
Test.instance.send(:private_test) # => "bar"

1 . Is the above a good Singleton pattern

Probably not. Using only class methods you don't get the benefit of having an initialize function executed for your single "instance", so it is missing some pieces you would normally find in a Singleton. Ruby is flexible enough so you can bolt on any missing features to the "class" object as needed, but it starts to look kind of ugly.

2 . Would this make sure there is only a single instance?

Yes. You are modifying the object which represents the class, and there is only one.

3 . Is there a way to have private methods using the singleton module?

Yes. Have you tried? Its just as you would expect.

class Test
  include Singleton
  def public_test
    "foo"
  end
  private
  def private_test
    "bar"
  end
end

Test.instance.public_test  # => "foo"
Test.instance.private_test # => throws exception
Test.instance.send(:private_test) # => "bar"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文