Builder
Step Builder: the builder enforces construction order.
#When to use it
When there are mandatory steps and order that the client cannot break.
public interface INeedHost { INeedPort WithHost(string host); }
public interface INeedPort { ICanBuild WithPort(int port); }
public interface ICanBuild { Connection Build(); }
public class ConnectionBuilder : INeedHost, INeedPort, ICanBuild
{
private string _host = ""; private int _port;
public static INeedHost Create() => new ConnectionBuilder();
public INeedPort WithHost(string host) { _host = host; return this; }
public ICanBuild WithPort(int port) { _port = port; return this; }
public Connection Build() => new(_host, _port);
}
// Forced usage:
var c = ConnectionBuilder.Create().WithHost("db").WithPort(5432).Build();Tradeoffs
| Pro | Con |
|---|---|
| Impossible to build the object incorrectly | Many interfaces — more code |
#creational #fluent #type-safe