Tuesday, July 14, 2009

Factory with java generics?

public class Driver {


public static void main(String[] args) {





InterfaceB b = Factory.create


(InterfaceB.class);


System.out.println(b);


InterfaceA a = Factory.create


(InterfaceA.class);


System.out.println(a);


}


}





class Factory {


static %26lt;T%26gt; T create(Class%26lt;T%26gt; c) {


if (c == InterfaceA.class) {


return (T)new ImplA();


} else if (c == InterfaceB.class) {


return (T)new ImplB();


}


else


{


throw new UnsupportedOperationException();


}


}


}





Is this the best way to make a factory using java Generics? Got any suggestions?

Factory with java generics?
The Factory pattern is powerful. It provides us with a framework for instantiating classes dynamically at run time according to the logic of the program.


see Example :


http://www.mailinator.com/tymagenerics.p...


http://blogs.tedneward.com/2006/12/01/Fo...


http://pag.csail.mit.edu/~adonovan/hacks...


http://www-128.ibm.com/developerworks/ja...


http://www.codeproject.com/useritems/Pow...


No comments:

Post a Comment