Sha256: 62948290f117b0a7efb385247e45274d8869153feacda78b9ad046441a0f5949

Contents?: true

Size: 1.84 KB

Versions: 1

Compression:

Stored size: 1.84 KB

Contents

#--
# =============================================================================
# Copyright (c) 2004, Jamis Buck (jgb3@email.byu.edu)
# All rights reserved.
#
# This source file is distributed as part of the Needle dependency injection
# library for Ruby. This file (and the library as a whole) may be used only as
# allowed by either the BSD license, or the Ruby license (or, by association
# with the Ruby license, the GPL). See the "doc" subdirectory of the Needle
# distribution for the texts of these licenses.
# -----------------------------------------------------------------------------
# needle website : http://needle.rubyforge.org
# project website: http://rubyforge.org/projects/needle
# =============================================================================
#++

require 'thread'

module Needle
  module Models

    # The definition of the "singleton" lifecycle service model. This will
    # result in immediate instantiation of the requested service, with a new
    # instance being returned the first time #instance is invoked, and that
    # same instance returned every time thereafter.
    #
    # This model is thread-safe.
    class Singleton

      # Create a new instance of the singleton service model.
      def initialize( container, opts={}, &callback )
        @container = container
        @callback = callback
        @mutex = Mutex.new
        @instance = nil
      end

      # Return the cached instance, if it exists. Otherwise, create new
      # instance by invoking the registered callback, caching the result.
      # Then return that instance.
      #
      # This method is thread-safe.
      def instance
        return @instance if @instance

        @mutex.synchronize do
          return @instance if @instance
          @instance = @callback.call( @container )
        end

        return @instance
      end
    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
needle-0.5.0 lib/needle/models/singleton.rb