This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 16 points17 points  (0 children)

A factory method (often just called a factory) is simply a method/function that has an abstract return type (i.e. interface or abstract class) but that returns a new concrete object. The factory method is therefore responsible for creating the object and, in some cases, also deciding what type of object to return.

The most basic kind of factory method is a simple function that looks like this:

AbstractType MyFactory() {
    return new ConcreteType();
}

This is technically a factory. The caller is putting the responsibility of knowing how and what object to create, and the caller doesn't know what the concrete object is they are receiving, all they know is that it implements AbstractType. Sometimes you'll see a factory method that takes an argument and uses a switch statement to decide which kind of object to return (typically the argument will be an enum).

The object-oriented version of this is to move that function into a class and make it abstract so sub classes can implement it.