Suppose you had a series of objects that needed constructed,
but your application needs to specialize how they are built. This is where
the builder pattern comes into play. It handles performing the building
of the necessary objects (also referred as the "product"); the
builder class has that sole responsibility. The builder class also supports
inheritance, which the product that the builder creates is usually involved in
the inheritance scheme, meaning that the derived builder objects are actually
building their related product object.
The builder pattern has a director that oversees the build process. The
director has a reference to the builder(s) available and is responsible for
invoking the correct method(s) in the builder. The builder has a common interface
that all builders derive from and that the director knows about, and because of
this, it can easily do its job. Inheritance plays a key, as the builder's
interface is abstract, and the derived builder classes actually do the work of
building an object. The resulting class that it builds can make use of
inheritance to provide a more specific implementation. The builder class
would be responsible for invoking the correct object.
It is possible that the builder/director relationship be dynamically created
through the use of a configuration file, though that adds a lot of work to the
software development process. More simplistically and realistically, this
relationship is statically created through a constructor or an initialization
method.
Listing 14
public class SecurityZone
{
private IAuthorizationManager _manager = null;
private IIdentity _user = null;
public SecurityZone(string userID, IAuthorizationManager manager)
{
_manager = manager;
}
private void GetUserInstance()
{
if (_user != null)
return;
if (_manager == null)
throw new ArgumentNullException("_manager");
_user = _manager.GetuserInstance();
}
public bool IsInRole(string roleName)
{
this.GetUserInstance();
return Roles.IsUserInRole(_user.Name, roleName);
}
}
In this case, the end product is the User, which is build
from a class that implements the IAuthorizationManager interface. The director
is the SecurityZone class that oversees the authorization process.