LoginSignup
0
0

More than 1 year has passed since last update.

[Ruby] 簡単例: Singleton(オブジェクト)

Last updated at Posted at 2021-09-12
本シリーズのトップページ
[Ruby] デザインパターンの簡潔サンプルコード集

概要

Singleton の概念などは省略.
単に Ruby でどう書くかだけを書き残す.

myclass.rb

singleton モジュールの取り込みによって、次が実現する
- new メソッドが非公開になる.
- クラスメソッド「instance」が定義される
- MyClass のインタンス変数には「instance」を使ってアクセスする

#!/usr/bin/env ruby
# -*- encoding: utf-8 -*-
# singleton モジュールの取り込みによって、次が実現する
# - new メソッドが非公開になる.
# - クラスメソッド「instance」が定義される
# - MyClass のインタンス変数には「instance」を使ってアクセスする

require 'singleton'

class MyClass
  include Singleton   #!
  attr_accessor :a

  def initialize
    puts "initialize が呼び出されました"
    @a = 0
  end
end

if __FILE__ == $0

  o1 = MyClass.instance
  p o1.a    # => 0
  o1.a = 4  #! 書き込み
  p o1.a    # => 4

  o2 = MyClass.instance
  p o2.a    # => 4

  p MyClass.instance.a  # => 4
end

参考書籍

・Rubyによるデザインパターン

以上

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