You are here:   ArielOrtiz.info > S/W Design and Architecture > Singleton Pattern

Singleton Pattern

Note: This is a class activity, nothing needs to be delivered.

  1. Create a folder called singleton. Inside this folder, create two files called: tigger.rb and tigger_test.rb.

  2. You are given the following Ruby class that models the famous Tigger character from A. A. Milne's “Winnie The Pooh” books:

    # File: tigger.rb
    
    class Tigger
    
      def to_s
        return "I'm the only one!"
      end
    
      def roar
        'Grrr!'
      end
    
    end
    

    Convert this class into a singleton using whatever technique you find fit. Place the resulting class in the tigger.rb source file.

  3. Check your solution using the following test case (place the test in the source file tigger_test.rb):

    # File: tigger_test.rb
    
    require 'minitest/autorun'
    require 'tigger'
    
    class TiggerTest < Minitest::Test
    
    
      def test_tigger
        t = Tigger.instance
        assert_same(t, Tigger.instance)
        assert_raises(NoMethodError) do # "new" method should be private!
          Tigger.new
        end
        assert_equal("I'm the only one!", t.to_s)
        assert_equal('Grrr!', t.roar)
      end
    
    end