Factory
From APIDesign
(Difference between revisions)
(New page: 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 ...) |
|||
Line 10: | Line 10: | ||
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. | 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. | ||
- | [[Category: | + | [[Category:APIDesignPatterns]] |
- | [[Category: | + | [[Category:APIDesignPatterns:Creational]] |
- | [[Category: | + | [[Category:APIDesignPatterns:Encapsulation]] |
Revision as of 12:26, 15 November 2008
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.