Coverage Report - org.trails.builder.BuilderDirector
 
Classes in this File Line Coverage Branch Coverage Complexity
BuilderDirector
0% 
0% 
0
 
 1  
 package org.trails.builder;
 2  
 
 3  
 import org.trails.exception.TrailsRuntimeException;
 4  
 
 5  
 import java.lang.reflect.Constructor;
 6  
 import java.util.HashMap;
 7  
 import java.util.Map;
 8  
 
 9  
 /**
 10  
  * Fulfils the "Director" role in the Trails implementation of
 11  
  * GOF's <a href="http://en.wikipedia.org/wiki/Builder_pattern">Builder pattern</a>
 12  
  *
 13  
  * Constructs an object using the Builder interface 
 14  
  */
 15  0
 public class BuilderDirector
 16  
 {
 17  
 
 18  0
         Map<Class, Builder> map = new HashMap<Class, Builder>();
 19  
 
 20  
         /**
 21  
          * Create a new instance of an object of class 'type' using a Builder.
 22  
          *
 23  
          * @param type is a class whose instance should be created
 24  
          * @return a newly created object
 25  
          */
 26  
         public <T> T createNewInstance(final Class<T> type)
 27  
         {
 28  0
                 Builder<T> builder = (Builder<T>) map.get(type);
 29  0
                 if (builder != null)
 30  
                 {
 31  0
                         return builder.build();
 32  
                 } else
 33  
                 {
 34  0
                         return createNewInstanceFromEmptyConstructor(type);
 35  
                 }
 36  
         }
 37  
 
 38  
         /**
 39  
          * Create a new instance of an object of class 'type' using an empty constructor.
 40  
          *
 41  
          * @param type is a class whose instance should be created
 42  
          * @return a newly created object
 43  
          */
 44  
         private <T> T createNewInstanceFromEmptyConstructor(final Class<T> type)
 45  
         {
 46  
                 try
 47  
                 {
 48  0
                         Constructor constructor = type.getDeclaredConstructor();
 49  0
                         constructor.setAccessible(true);
 50  0
                         return (T) constructor.newInstance();
 51  
 
 52  0
                 } catch (Exception ex)
 53  
                 {
 54  0
                         throw new TrailsRuntimeException(ex, type);
 55  
                 }
 56  
         }
 57  
 }