Sha256: 1239409b63108a92fbd3d18ab7babcdecd2190315668f56169d2d59ed25b8deb

Contents?: true

Size: 1.92 KB

Versions: 1

Compression:

Stored size: 1.92 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 'needle/models/proxy'
require 'thread'

module Needle
  module Models

    # The definition of the "singleton-deferred" lifecycle service model.
    # This will result in deferred 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 SingletonDeferred

      # Create a new SingletonDeferred 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
      # Proxy instance that wraps the container and callback references of
      # this service model, and cache it. Then return that instance.
      #
      # This method is thread-safe.
      def instance
        return @instance if @instance

        @mutex.synchronize do
          return @instance if @instance
          @instance = Proxy.new( @container, &@callback )
        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-deferred.rb