Friday, 6 May 2011

Generic Factory Class - Sample

Previously I’ve talked about generic classes and generic methods. This blog combines the two and demonstrates how to write a generic factory class. Now, as this is a blog, we’re keeping it simple and assuming that the classes we wish to use our factory to create have a default no-arg constructor and are public - you can add extra detail in to deal with constructor args.

Firstly, we need to write our factory class:

public class Factory<T> {

 
// T type MUST have a default constructor
 
private final Class<T> type;

 
public Factory(Class<T> type) {

   
this.type = type;
 
}

 
/**
   * Use the factory to get the next instance.
   */
 
public T getInstance() {

   
try {
     
// assume type is a public class
     
return type.newInstance();
   
} catch (Exception e) {
     
throw new RuntimeException(e);
   
}
  }

 
/**
   * Create the factory. Note that V can be T, but to demonstrate that
   * generic method are not generic classes, I've called it V and not T.
   * In using this method V becomes T.
   */
 
public static <V> Factory<V> getInstance(Class<V> type) {

   
return new Factory<V>(type);
 
}
}

Note that the factory object itself is created using a static factory method getInstance(...), which will reduce the amount of typing in the client code.

In running this sample, I use the same factory code to create a String and a sample TestOne class.

  public static void main(String[] args) {

   
Factory<String> factory = Factory.getInstance(String.class);

    String sample = factory.getInstance
();
    System.out.println
("Sample is: " + sample);

    Factory<TestOne> factory2 = Factory.getInstance
(TestOne.class);

    TestOne sample2 = factory2.getInstance
();
    System.out.println
("Sample is: " + sample2);
 
}

 
public static class TestOne {

   
@Override
   
public String toString() {

     
return "This is TestOne";
   
}
  }

You can add lots of extra features in here to make this a real factory, but this demonstrates the principal...

No comments: