Monday, October 26, 2009

Java API FTW

I'm no big fan of software engineering in general, and if you're not, you might as well just scroll on by here, but if you're looking to implement the Factory pattern, did you know that Java has a built in generic class called Class? All you've got to do is
  1. define an abstract parent class for your objects, (called PARENT here)
  2. with an abstract method that returns an object of its type, (called CREATE here) and then
  3. define the class that's going to generate your objects (called FACTORY here),
  4. with a method that looks something like:
You need childClass.newInstance() because you can't initialize a generic class (which makes sense since, if you could, in this case you can't guarantee that the child even implements a constructor, since the abstract PARENT class doesn't have to).

As well, this actually throws an unchecked casting warning, so it probably needs a little tweaking. But everything else seems to upgrade the issues from a class cast warning (that you know of course won't happen, since C extend PARENT, and PARENT is abstract, and has abstract method CREATE that returns an object of class C)--from a class cast warning to a full-blown compiler error with the generics, so...

No comments:

Post a Comment