Factory and Collection Style Collections

Visual LANSA

Factory and Collection Style Collections

There are two different ways of creating a keyed collection, one with collection style Factory and one with collection style Collection.

By default the Style property of a keyed collection is Factory. This means that a new item in the collection is created whenever the collection is accessed using a value in the key field that does not already exist in the collection.

Alternatively the Style can be Collection. This means that the application must explicitly create the items in the collection by using a SET_REF command.

The advantage of using references is that you can have direct control over memory usage by explicitly creating and destroying components. The larger and more complex your application is, the more important it becomes to ensure that your application uses memory effectively.

Factory Collections

For any given object called #Object defined in a collection like this (where the default Style() is shown):   

 

      Define_Com Class(#Prim_KCol<#Object #Key>) Name(#Collection)  Style(Factory)

 

any reference to an item in the collection, for example: 

      Set #Collection<#Key>   ................

 

will automatically create an instance of #Object if an object with key #Key is not already in the collection.

Collection Style Collections

If the collection is defined like this:

 

      Define_Com Class(#Prim_KCol<#Object #Key>) Name(#Collection) Style(Collection) 

 

then

       

      Set #Collection<#Key>   ................

 

will fail with an error message if an object with key #Key is not already in the collection.  To handle a Style(Collection) collection correctly in this situation you need to code this:

      If_Ref  #Collection<#Key> is(*null)

         Set_Ref #Collection<#Key> To(*Create_as #Object)
      Endif
 
      Set #Collection<#Key>   ................

 

This code first checks whether #Collection<#Key> exists in the collection. If it does not then a Set_Ref command is used to create a new instance of #Object and then assign the reference to the new object into the collection.    

This may seem like more code, but in fact Style(Collection) collections are very useful because you can check whether something exists in the collection and then control when and how it is added.

Note that only keyed collections support the Style(Factory) and Style(Collection) properties. All other collection types (eg: array, list, sorted array, etc) are implicitly Style(Collection) collections.