Skip to main content

Pattern: Factory

A factory is a function or method that returns objects of a varying prototype or class from some method call, which is assumed to be new.

Purpose of .NET implementation

For getting data from Web, you can have a HttpWebRequest or FtpWebRequest.
The type of the request depends on the protocol you want to use : HTTP or FTP.
You want to make easier for the developer to create the appropriate request object based on the string that starts with the protocol.
So you can have the Factory pattern method : WebRequest.Create.

Example in .NET :

Factory

Factory example for Pattern Factory
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Internal;
using System.Data.Common;
using System.Globalization;
using System.Net;
using System.Web.Mvc;

namespace Factory;
internal class FactoryDemo
{
public static void DemoWebRequest()
{

//WebRequest.Create is a factory - can create HttpWebRequest or FtpWebRequest
HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create("http://www.yahoo.com");

}
public static void DemoConvert()
{
string value = "1,500";
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");

Console.WriteLine(Convert.ToDouble(value));

Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("fr-FR");
Console.WriteLine(Convert.ToDouble(value));

}
static void RegisterControllerFactory()
{
ControllerBuilder.Current.SetControllerFactory(new MyControllerFactory());
}
}

//default controller factory is a factory of controllers
class MyControllerFactory : System.Web.Mvc.DefaultControllerFactory
{

public override IController CreateController(System.Web.Routing.RequestContext requestContext, string controllerName)
{
if (controllerName == "andrei")
return null;//maybe controller not found

return base.CreateController(requestContext, controllerName);
}
}

Download source

See Source Code for Microsoft implementation of Factory

SourceCode Convert.ToDouble
SourceCode DefaultControllerFactory
SourceCode WebRequest.Create

Learn More

C2Wiki
dofactory
DPH
Hammer Factories
Wikipedia

Homework

You want to create multiple types of drinks( water, tea, coffee).
With an IDrink interface create a factory method ( with a parameter ) to create a drink.