6
0

この記事は何

デザインパターンについて、Rubyでどのような使い方ができるかをまとめた記事です。
デザインパターン自体の解説は詳しく行いません。

Singletonパターンとは

Singletonパターンとは、特定のクラスがインスタンスを一つのみしか生成しないことを保証するためのデザインパターンです。

詳しくはこちらをご覧ください。

Rubyでのコード例

単純な実装を行うと、以下のようになります。

class Singleton
  private_class_method :new

  class << self
    def instance
      @instance ||= new
    end
  end
end

puts Singleton.instance == Singleton.instance
出力結果
true

また、RubyにはSingletonモジュールがあるため、mixinするだけでSingletonなクラスを作ることが可能です。

require 'singleton'

class SingletonClass
  include Singleton
end

puts SingletonClass.instance == SingletonClass.instance
出力結果
true

どのような時に使えるか

正直Singletonは使い所が難しいデザインパターンで、実際Rubyで作成したアプリケーションに実装をしたことはあまりありません。
Singletonの難しさについては以下のような記事でも紹介されています。

Singletonパターンで実現したいユースケースは

  • 何かしらの理由で特定のクラスのインスタンスの生成を一つのみにしたい
  • クラスメソッドではなく、インスタンスの形を取って使いまわせるようにしたい(インターフェースの適応など)

のようなレアなケースになるため、普段から多用するようなデザインパターンではないということなのかもしれません。

6
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
6
0