LoginSignup
0

More than 5 years have passed since last update.

rubyで簡易Singleton

Posted at

みなさん、rubyでSingletonパターンを実装するときにはどうしていますか?
多くの人が標準ライブラリのsingletonパッケージにあるSingletonモジュールを使っていると思います。

require 'singleton'

class MyClass
  include Singleton

  def initialize
    @instance_var = 'hoge'
  end

  def my_func
    return @instance_var
  end
end

puts MyClass.instance.my_func # => hoge

でも、いちいち.instanceって書くのめんどくさいですよね。。。

なので、クラスオブジェクトをシングルトンクラスのオブジェクト代わりに使ってみました。

module MyClass
  module_function

  @instance_var = 'hoge'

  def my_func
    return @instance_var
  end
end

puts MyClass.my_func # => hoge

インスタンス変数の代わりにクラスインスタンス変数を使っているのがポイントです。

Singletonモジュールを使う場合との比較を載せておきます。

Singletonモジュールをインクルード クラスオブジェクトを利用
シングルトンにする方法 include Singleton module_function
初期化の方法 initialize クラス定義の中で行う
初期化のタイミング 最初にinstanceを読んだ時 クラスが書かれたファイルをrequireした時
状態の保持をする変数 クラス変数 クラスインスタンス変数

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
0