Factory Method

AKA: Virtual Constructor

In many languages, creating an object requires you to know what that object will be. However, sometimes you only know the base type to be constructed and when to construct, not the specifics.

For example, you might wish to open a file by URL. The prefix or path might indicate a specific type, but the caller only knows it must be a file handle. A generic solution can map regular expressions or other types of matcher to a key-value store of factory methods where each creates a specific kind of object to handle the file open request. Consider a URL for a local file, a networked file that might need buffering, a memory-backed file that might need emulating from within the program, or a pipe that opens a stream to another process.

A file handle can manage all those examples, but the object behind the handle is different. We must create the object based on some other information. In some systems, it’s decided upon just in time as per the file opening via URL. Other times, we handle it as part of the configuration, such as when you configure the kind of UI used for an error or request for user input (such as with CreateFileDialogue) or when the creation is relative to the subject of the created object as per creating editing tools directly from the objects to be edited.

In effect, Factory Method is the nominalisation of construction specifics when you don’t have a way to reference a constructor in the same way we can store a reference to functions. The constructing object won’t need to know which concrete type it must construct and can even build objects added later by dynamically loaded code, e.g. by plugins.

“I make benches. What type of bench? That doesn’t matter. I was instructed by someone else on what style to produce. You just tell me how many they should seat and where you need them.”