Programing

루비의 싱글 톤 클래스는 정확히 무엇입니까?

lottogame 2020. 10. 21. 07:36
반응형

루비의 싱글 톤 클래스는 정확히 무엇입니까?


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는 싱글 톤 메소드 만 보유하는 클래스를 자동으로 생성합니다. 새로 생성 된 클래스를 싱글 톤 클래스라고합니다.


    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를 이해하는 데 정말 도움 되었으며 좋은 코드 예제가 있습니다.


@Pistos 답변으로 업데이트하면 버전 1.9.2 ruby에서 단일 클래스를 얻기 위해 새로운 구문을 추가합니다.

 singleton_class = ( class << foo; self; end )

다음으로 대체 할 수 있습니다.

singleton_class = foo.singleton_class

https://apidock.com/ruby/Object/singleton_class


The most pragmatic/action-oreinted way to think of it (IMHO) is: as an inheritance chain, or method lookup/resolution order. This picture might help

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

This is r 1.9, contrasting builtin and user-defined classes: i'm still digesting this one.

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

Also, i htink a confusing use of the term is "Singleton object", which is different concept. A singleton object comes from a class which has its constructor/instantiator method overridden so that you can allocate only one of that class.

참고URL : https://stackoverflow.com/questions/212407/what-exactly-is-the-singleton-class-in-ruby

반응형