Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Brandon Burrus edited this page Jan 18, 2021 · 1 revision

Factory methods allow base classes to defer the construction of something to subclasses, usually relying on an interface instead of a concrete implementation.

A --creates--> B
^              ^
|              |
C --defines--> D

In the above example, A needs to create the interface B but allows its subclass C to define which exact concrete implementation of C to use (aka D).


The static version of factory methods are alternatives to constructors, in that they create an instance of their defining class. The benefit of which is that 1) the constructor becomes named, 2) the returned instance can be refactored later to be a sub-type, and 3) enables construction logic to be moved out of constructors themselves.

Clone this wiki locally