'. '

Factory

From APIDesign

Jump to: navigation, search

Factory method is well know design pattern useful in API design too. In general, instead of making constructor of some class public, you can reveal a public static method that returns instance of the class:

Code from ServerConnector.java:
See the whole file.

public static ServerConnector create(
    NameProvider nameProvider, 
    URLProvider urlProvider, 
    ResetHandler reset
)
 

This has few benefits from the point of API evolution:

  • the class is not subclassable, which solves a lot of nasty evolution problems by itself
  • one can create a cache or have pool of instances to return
  • the whole factory method can be synchronized, preventing parallel access
  • one can return subclass of the return type, not the type itself

All these details can be implemented and are hidden to some extent from the user of the API. It is impossible to achieve this with plain constructor.

Personal tools
buy