Software Design Patterns in Practice: Factory Pattern with Generics Author: Erkan YASUN, Software Architect – Radar Electronic Warfare GroupIn software engineering world, Factory Design Pattern is used to encapsulate object creation. Generics which is another useful concept, converts runtime typecast errors to compile-time errors. Besides these benefits, Factory Design Pattern and Generics provide a simple approach to manage software problems. With the combination of these two concepts, we can multiply the benefits.For the following types of work Generics with Factory Design Pattern may be used.Class-specific serialization/deserialization for different types of classesMessaging via bus (TCP, UDP etc.)Converting different types of message objects into binary data for writing socketConverting binary data from socket reading into different types of message objectsCreating binary file from Java objects (objects belong to different classes)Creating Java objects by parsing a binary file (objects belong to different classes)Class-specific calculation operations for different types of classesLet’s consolidate with a sample. Assume that we have developed a simple ability calculating the area of a given geometrical shape, and having the following requirement set;The function shallcalculate the area of a given triangle.calculate the area of a given rectangle.calculate the area of a given circle.change the existing area calculation function with another calculation function.add area calculation function for a new geometrical shape.a. Factory Design Pattern without GenericsWhen we developed without generics according to the given requirements, we obtain a class diagram similar to the following:When we examine the following RectangleAreaCalculator class, we will see that the parameter cannot be used without typecast.The following code fragment illustrates the sample use of the area calculation. When we run this sample code, we will get ClassCastException. As “areaCalculatorFactory.getCalculator(circle.getClass())” returns instance of CircleAreaCalculator, we cannot use it. Although compiler does not give any warning, running the application will be resulted with runtime error. (You can see runtime error in the Console tab.) b. Factory Design Pattern with GenericsWhen we developed with generics according to the given requirements, we obtain a class diagram similar to the following. In the Rectangle Area Calculator class below, it is seen that the shape parameter can be used without typecast.The following code fragment illustrates the sample use of the area calculation. It also shows how Generics provides “type safety” by converting runtime errors to compile-time errors. (You can see the compile error in the Problems tab.)All in all, considering the benefits illustrated above with the examples, using Factory Design Pattern with Generics will provide uncomplicated approach to handle software problems.