AlgoViz

Factory method

medium 60 min

A fixed workflow with one open step that creates an object.

Watch lesson4:53

Where it shows up

The same pattern appears across everyday software.

  • Python logging

    `Logger.makeRecord` is described in the documentation as a factory method that subclasses can override to create specialized `LogRecord` objects. `getLogger`, in contrast, returns one shared logger per name.

  • Java collections

    `Iterable.iterator()`: each collection decides which iterator it returns, and the for-each loop is the workflow that uses it.

  • Java executors

    `AbstractExecutorService.newTaskFor` creates the task that submit runs. Subclasses override it to return their own `RunnableFuture`. The default is `FutureTask`.

  • Java ThreadFactory

    An object that creates threads on demand, so that thread pools contain no call to new Thread. Passed in, not inherited.

  • Swing JTable

    `createDefaultColumnModel` and its siblings are protected and return the default models. A subclass overrides them.

  • ADO.NET

    `DbConnection.CreateDbCommand` is protected and abstract: each database provider returns its own command object.

  • Qt item delegates

    `createEditor` is virtual and returns the widget used to edit a cell. Override it to offer another editor.

  • Django editing views

    `get_form_class` and `get_form` decide which form a view creates. A class attribute covers the simple case, the method the rest.

  • Spring

    `BeanFactory` is the root interface of the container, a registry that creates objects by name or type. `AbstractFactoryBean.createInstance` is a factory method that subclasses must override.

  • React createElement

    Creates an element from a type that is passed in: a tag name or a component. A creating function that decides by its argument, close to a simple factory.

  • Plugins

    Java `ServiceLoader` and Python entry points let installed packages declare providers that a program finds at run time: a registry across packages.