I am currently attempting to understand the fundamentals of factory methods in Java and I found a lot of exampels where a pattern like this has been used.
I got some exercises about sorting algorithms where one task is to write a factory class for all existing algorithms but with the requirement that newly added algorithmes can be integrated via "plug and play". That phrase itched me.By using the switch case
solution I would be unable to add Algorithms without rewriting the factory class so I came up with this:
SorterFactory.java
public final class SorterFactory
{
private SorterFactory()
{
}
public static Sortierer.Sorter getNewSorter( Sorts sorts )
{
try
{
return (Sortierer.Sorter) Class.forName( sorts.getName() ).getConstructor().newInstance();
}
catch ( ClassNotFoundException | InstantiationException | IllegalAccessException
| IllegalArgumentException | InvocationTargetException | NoSuchMethodException
| SecurityException e )
{
e.printStackTrace();
// further exception handling
}
}
}
Sorts.java
public final class Sorts
{
private String name;
// hardcoded for test purpose.
// will be imported from XML-file
public static final Sorts HEAPSORT = new Sorts( HeapSort.class.getName() );
public static final Sorts MERGESORT = new Sorts( MergeSort.class.getName() );
public static final Sorts BUBBLESORT = new Sorts( BubbleSort.class.getName() );
public static final Sorts INSERTSORT = new Sorts( InsertSort.class.getName() );
public static final Sorts QUICKSORT = new Sorts( QuickSort.class.getName() );
public static final Sorts TRUEHEAPSORT = new Sorts( TrueHeapSort.class.getName() );
private Sorts( String name )
{
this.name = name;
}
public String getName()
{
return name;
}
}
So why is the switch case
approach much more favored above this kind of solution in terms of safety,security and performance? Also is it useful to box the names in a class to prevent the misusage of the factory method instead of allow Strings as arguments?
Thanks for any advice and criticism.