New page: Builder pattern is build around configuration cumulative factory pattern followed by final call to a [[APIDesignPatter...
New page
[[APIDesignPatterns:Builder|Builder pattern]] is build around configuration [[APIDesignPatterns:CumulativeFactory|cumulative factory]] pattern followed by final call to a [[APIDesignPatterns:Factory|factory method]]. It is very useful, especially in cases where the intermediate states created by the use of [[APIDesignPatterns:CumulativeFactory|cumulative factory]] are incomplete and cannot be used by itself. If an additional action (write to disk, establish connnection, etc.) is needed, it makes sense to finish the API calls by final use of [[APIDesignPatterns:Factory|factory method]].
Imagine that we have an API representing a server:
<source lang="java" snippet="aserverinfo.builder.api"/>
And we need a way to establish connection to it. For that purpose we can define additional class that has no ''getters'', no way to obtain its state via external APIs. Instead it offers users of its API only ''setters'' (or in this case cumulative factory methods) allowing the clients to change enough properties before final creation of the connector:
<source lang="java" snippet="aserverinfo.builder.factory"/>
The use is similar as in case of [[APIDesignPatterns:CumulativeFactory|cumulative factory]], just the writer of the API can simplify internals of the '''ServerInfo''' class, as it is know to never connect directly, to the server, it is just a recipe for creation of the connection:
<source lang="java" snippet="ServerConnector.builder.creation.verbose"/>
The previous snippet is the verbose way to use the API, the shorter one liner looks like:
<source lang="java" snippet="ServerConnector.builder.creation"/>
[[APIDesignPatterns:Builder|Builder pattern]] evolution characteristics are simpler to [[APIDesignPatterns:CumulativeFactory|cumulative factory]] pattern, yet in some situations can its use simplify internal implementation of the [[API]].
[[Category:APIDesignPatterns]]
[[Category:APIDesignPatterns:Creational]]