Factory Pattern Example in .NET
The factory method design pattern is used to hide the actual subclass constructor call used for a certain parameter, thus gaining flexibility. It is one of the most widely used design patterns in general and you might even not have noticed it’s there.
A commonly used example, which you might have not noticed, is the Image.FromFile call in .NET. This allows you to instantiate a particular kind of image, depending on the actual file given as parameter.
Image im = Image.FromFile”image.bmp”);
For a bitmap file (.bmp), an instance of the Bitmap class is created. Note that in .NET BCL (Base Class Library), the Image class is abstract and thus cannot be instantiated by itself. The base class (Image) offers a static method (FromFile) that calls the constructor for the appropriate subclass (Bitmap) and return the instance variable.
I find this a simple, but great example of applied design pattern.
Other use of the factory method in the BCL is described here:
A more pure example of this pattern is the System.Net.WebRequest class, used to make a request and receive a response from a resource on the Internet. FTP, HTTP, and file system requests are supported by default. To create a request, call the Create method and pass in a URI. The Create method itself determines the appropriate protocol for the request and returns the appropriate subclass of WebRequest: HttpWebRequest, FtpWebRequest (new to the .NET Framework 2.0), or FileWebRequest. The caller doesn’t need to know the specifics of each protocol, only how to invoke the factory and work with the WebRequest that gets returned. If the URI changes from an HTTP address to an FTP address, the code won’t have to change at all.