Factory Design pattern - Asp.net

Factory Design Pattern is already being used in Asp.net.

It is useful when all related classes are grouped and we can decide which class needs to be instantiated at run time.


The Factory Design pattern is used when a class cannot anticipate the type of object it must create or when you want to delegate the responsibility of creations of object to another class so that you need not worry about the complexity involved in creation of the object. This reduces the code redundancy in the application.

Simple examples
1) int intValue = Convert.ToUInt16 (true);

This method internally checks parameter data type. It then converts this Boolean value into the integer value “1” and returns it.

2) SqlCommand
Classic examples of .NET are enumerators, such as
CommandType.StoredProcedure,
CommandType.TableDirect
CommandType.Text.
SqlCommand cmdobj = newSqlCommand (StoredProcedureName, Connection String);
cmdobj.CommandType =CommandType.StoredProcedure;

SqlCommand cmdobj = new SqlCommand (TableName, ConnectionString);
cmdobj.CommandType = CommandType.TableDirect;

SqlCommand cmdobj = new SqlCommand (SelectText, ConnectionString);
cmdobj.CommandType = CommandType.Text;

3) Custom Example
Every application uses logging to log messages for debugging, analyzing or auditing. There can be various types of logging like logging to text file, logging to event logger or to SQL server, etc. The application should not have the knowledge of which logger it is using and hence it should be abstracted from the creation of the logger component. For this to happen, the responsibility of creating the logger component is given to a special class knows as the LoggerFactory. This class knows how to create different kind of loggers, what are the parameters to be set for each type of logger, etc. Now the application need not know about the logger creation, it will ask the Factory to create a corresponding logger (which is configured) and start using it.

4) HTTP handlers
ASP.NET provides the capability of routing http requests to an object of the class that implements the IHttpHandlerFactory interface. Here, ASP.NET utilizes the Factory design pattern. This pattern provides an interface for creating families of related objects without specifying their concrete classes. In simple terms, you can consider such a class as a factory that creates http handler objects depending on the parameters passed to it. We don't have to specify a particular http handler class to instantiate; http handler factory takes care of it. The benefit of this is if in the future the implementation of the object that implements the IHttpHandler interface changes, the consuming client is not affected as long as the interface remains the same.

Popular Posts