1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rubyのシングルトンクラスについて

Last updated at Posted at 2018-03-24

シングルトンクラスについて、すぐに忘れるので、メモしておく。

この内容はメタプログラミングRubyに書いている内容です。

ここでは、特異クラス=シングルトンクラスのこと。
シングルトンパターンのシングルトンの意味合いではない。

シングルトンメソッド

オブジェクト固有のメソッドを以下のように定義することができる。

class C
end

 c = C.new
 #シングルトンメソッド定義
 def c.singleton_method_method_test
  p "singleton_method_test"
 end

 c.singleton_method_test

このメソッドは、シングルトンクラスに定義される。
シングルトンクラスは、オブジェクトとクラスの間に位置する存在である。

  c.singleton_class.instance_methods(false)
  #ここにいる
  [:singleton_method_test]

クラスメソッドへの応用

クラスメソッドも、これと同じ仕組みで定義されている。

class C
  def self.class_method_test
    p "class_method_test"
  end
end

C.singleton_class.instance_methods(false)
=> [:class_method_test]

あるオブジェクトからメソッドを呼び出すときは、以下のようなメソッドのたどり方になる。

オブジェクトからシングルトンクラスを(一度)参照し、その後シングルトンクラスから継承チェーンをsuperclassによって辿ってメソッドを探していく。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?