Ruby中的单例类是什么?

看起来好像我错过了这个观点或者误解了Ruby中单例类的重要性。 我听过并且以多种方式阅读过它 - 有些比其他更复杂 - 但我对它是什么感到困惑。 它本身是一个阶级吗? 这是所有对象属于“课堂”的原因吗? 这个概念很模糊 ,但我相信它与我为什么可以定义一个类方法(class foo; def foo.bar ...)有关。

那么:Ruby中的单例类是什么?


首先是一个小的定义: 单例方法是仅为单个对象定义的方法。 例:

irb(main):001:0> class Foo; def method1; puts 1; end; end
=> nil
irb(main):002:0> foo = Foo.new
=> #<Foo:0xb79fa724>
irb(main):003:0> def foo.method2; puts 2; end
=> nil
irb(main):004:0> foo.method1
1
=> nil
irb(main):005:0> foo.method2
2
=> nil
irb(main):006:0> other_foo = Foo.new
=> #<Foo:0xb79f0ef4>
irb(main):007:0> other_foo.method1
1
=> nil
irb(main):008:0> other_foo.method2
NoMethodError: undefined method `method2' for #<Foo:0xb79f0ef4>
        from (irb):8

实例方法是类的方法(即在类的定义中定义)。 类方法是Class实例上的单例方法 - 它们没有在类的定义中定义。 相反,它们是在对象的单例类中定义的。

irb(main):009:0> Foo.method_defined? :method1
=> true
irb(main):010:0> Foo.method_defined? :method2
=> false

您可以使用语法class << obj打开对象的单例类。 在这里,我们看到这个单例类是单例方法定义的地方:

irb(main):012:0> singleton_class = ( class << foo; self; end )
=> #<Class:#<Foo:0xb79fa724>>
irb(main):013:0> singleton_class.method_defined? :method1
=> true
irb(main):014:0> singleton_class.method_defined? :method2
=> true
irb(main):015:0> other_singleton_class = ( class << other_foo; self; end )
=> #<Class:#<Foo:0xb79f0ef4>>
irb(main):016:0> other_singleton_class.method_defined? :method1
=> true
irb(main):017:0> other_singleton_class.method_defined? :method2
=> false

因此,向对象添加单例方法的另一种方法是使用打开的对象的单例类来定义它们:

irb(main):018:0> class << foo; def method3; puts 3; end; end
=> nil
irb(main):019:0> foo.method3
3
=> nil
irb(main):022:0> Foo.method_defined? :method3
=> false

综上所述:

  • 方法必须总是属于一个类(或者:是某个类的实例方法)
  • 普通方法属于它们定义的类(即类的实例方法)
  • 类方法只是一个Class单例方法
  • 对象的单例方法不是对象类的实例方法; 相反,它们是对象的单例类的实例方法。

  • Ruby提供了一种方法来定义特定于特定对象的方法,这种方法称为Singleton方法。 当一个对象声明一个单例方法时,Ruby会自动创建一个只包含单例方法的类。 新创建的类称为Singleton类。

    
        foo = Array.new
        def foo.size
          "Hello World!"
        end
        foo.size  # => "Hello World!"
        foo.class # => Array
        #Create another instance of Array Class and call size method on it
        bar = Array.new
        bar.size  # => 0
    
    Singleton类是自动创建并插入到继承层次结构中的特定于对象的匿名类。

    可以在对象上调用singleton_methods以获取对象上所有单例方法的名称列表。

        foo.singleton_methods  # => [:size]
        bar.singleton_methods  # => []
    

    这篇文章确实帮助我理解了Ruby中的Singleton Classes,它有一个很好的代码示例。


    以最实用/最实际的方式来思考它(恕我直言)是:作为继承链或方法查找/解决顺序。 这张照片可能有帮助

    http://www.klankboomklang.com/2007/11/25/modules-part-i-enter-the-include-class/

    这是r 1.9,对比内置和用户定义的类:我仍然在消化这个。

    http://d.hatena.ne.jp/sumim/20080111/p1

    另外,我对这个术语的混淆使用是“单一对象”,这是不同的概念。 一个单例对象来自一个类,它的构造函数/实例化方法被覆盖,所以你只能分配一个类。

    链接地址: http://www.djcxy.com/p/95423.html

    上一篇: What exactly is the singleton class in ruby?

    下一篇: Declaring variables in .rb file result unwanted output