Class: Copland::ClassFactory

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/copland/class-factory.rb

Overview

This factory class provides an interface for instantiating a variety of different kinds of classes. It uses the concept of a “pool” to allow different functional groupings of classes to be separated within the factory. Thus, this is the factory class for all classes in Copland, including configuration points, instantiators, and service models.

Instance Method Summary collapse

Constructor Details

#initializeClassFactory

Create a new ClassFactory. By default, it defines no pools.



47
48
49
50
# File 'lib/copland/class-factory.rb', line 47

def initialize
  @pools = Hash.new
  @constructors = Hash.new
end

Instance Method Details

#create_pool(name, &block) ⇒ Object

Define a new pool with the given name. If a block is given, it should accept at least one parameter (the klass to instantiate) and should return an instance of that class. Additional parameters may be passed to the block, with the intent that they may be used to initialize the new object somehow.



57
58
59
60
61
# File 'lib/copland/class-factory.rb', line 57

def create_pool( name, &block )
  block ||= proc { |k,*args| k.new( *args ) }
  @pools[ name ] = Hash.new
  @constructors[ name ] = block
end

#get(pool_name, name, *args) ⇒ Object

Return a new instance of the class registered under the given name in the given pool. If any additional arguments are given to the method, they will be passed to the constructor used to instantiate the class.



82
83
84
85
86
87
88
89
90
91
# File 'lib/copland/class-factory.rb', line 82

def get( pool_name, name, *args )
  pool = get_pool( pool_name )

  klass = pool[ name ]
  raise NoSuchRegisteredClassException, "#{pool_name}:#{name}" unless klass

  constructor = @constructors[ pool_name ]

  return constructor.call( klass, *args )
end

#get_pool(name) ⇒ Object

Retreive a reference to the pool with the given name. If no such pool exists, a NoSuchPoolException will be raised.



65
66
67
68
69
# File 'lib/copland/class-factory.rb', line 65

def get_pool( name )
  pool = @pools[ name ]
  raise NoSuchPoolException, name unless pool
  return pool
end

#register(pool_name, name, klass) ⇒ Object

Register the given klass with the class factory, in the given pool, with the given name. If the given pool does not exist, a NoSuchPoolException will be raised.



74
75
76
77
# File 'lib/copland/class-factory.rb', line 74

def register( pool_name, name, klass )
  pool = get_pool( pool_name )
  pool[ name ] = klass
end