Skip to content

Factory Pattern Example in .NET

April 6, 2009

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.

No comments yet

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: