Search code examples
javafactoryfactory-pattern

Java Factory patterns


Here is a factory "inner class?" from the Java Jung graph package:

   Factory<Graph<String, Integer>> graphFactory = new Factory<Graph<String, Integer>>()
   {
       public Graph<String, Integer> create()
       {
           return new SparseMultigraph<String, Integer>();
       }
   };

What I want to know is what programming language concept is the above? Especially what is this concept in Java? Is the above an inner class? It is clearly not a method. It seems odd to me because it constructs a Factory object and then has braces with a semicolon at the end with a method to create a graph.


Solution

  • It is an anonyous inner class. The above code creates a subclass of the Factory class (or a class implementing the Factory interface), overrides its create() method, calls its constructor, and assigns the result to the graphFactory variable.