it communicates with a production database that isn't always available), then the creation of Dangerous objects is placed in the virtual factory method createDangerous in class Foo. For testing, TestFoo (a subclass of Foo) is then created, with the virtual factory method createDangerous overridden to create and return FakeDangerous, a fake object. Unit tests then use TestFoo to test the functionality of Foo without incurring the side effect of using a real Dangerous object. Benefits and variants Besides use in design patterns, factories, especially factory methods, have various benefits and variations. Descriptive names A factory method has a distinct name. In many object-oriented languages, constructors must have the same name as the class they are in, which can lead to ambiguity if there is more than one way to create an object (see overloading). Factory methods have no such constraint and can have descriptive names; these are sometimes known as alternative constructors. As an example, when complex numbers are created from two real numbers the real numbers can be interpreted as Cartesian or polar coordinates, but using factory methods, the meaning is clear, as illustrated by the following example in C#. public class Complex { public double real; public double imaginary; public static Complex FromCartesian(double real, double imaginary) { return new Complex(real, imaginary); } public static Complex FromPolar(double modulus, double angle) { return new Complex(modulus * Math.Cos(angle), modulus * Math.Sin(angle)); } private Complex(double real, double imaginary) { this.real = real; this.imaginary = imaginary; } } Complex product = Complex.FromPolar(1, Math.PI); When factory methods are used for disambiguation like this, the raw constructors are often made private to force clients to use the factory methods. Encapsulation Factory methods encapsulate the creation of objects. This can be useful if the creation process is very complex; for example, if it depends on settings in configuration files or on user input. Consider as an example a program that reads image files. The program supports different image formats, represented by a reader class for each format. Each time the program reads an image, it needs to create a reader of the appropriate type based on some information in the file. This logic can be encapsulated in a factory method. This approach has also been referred to as the Simple Factory. Java public class ImageReaderFactory { public static ImageReader createImageReader(ImageInputStreamProcessor iisp) { if (iisp.isGIF()) { return new GifReader(iisp.getInputStream()); } else if (iisp.isJPEG()) { return new JpegReader(iisp.getInputStream());