Class: Needle::Models::SingletonDeferred

Inherits:
Object
  • Object
show all
Defined in:
lib/needle/models/singleton-deferred.rb

Overview

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.

Instance Method Summary collapse

Constructor Details

#initialize(container, opts = {}, &callback) ⇒ SingletonDeferred

Create a new SingletonDeferred service model.



32
33
34
35
36
37
# File 'lib/needle/models/singleton-deferred.rb', line 32

def initialize( container, opts={}, &callback )
  @container = container
  @callback = callback
  @mutex = Mutex.new
  @instance = nil
end

Instance Method Details

#instanceObject

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.



44
45
46
47
48
49
50
51
52
53
# File 'lib/needle/models/singleton-deferred.rb', line 44

def instance
  return @instance if @instance

  @mutex.synchronize do
    return @instance if @instance
    @instance = Proxy.new( @container, &@callback )
  end

  return @instance
end