Today I will show how to implement factory design pattern in NET platform.
One type of pattern that we see again and again in OO programs is the Factory pattern.
A Factory pattern is one that returns an instance of one of several possible classes, depending on the data provided to it.
Consider the following C# code sample:
using System;
using System.Runtime.Remoting;
namespace Factory
{
/// /// implements factory design pattern ///
public static class WorkerFactory
{
private static string _asmName = "MyAssembly.";
//returns new worker object
public static void CreateWorker(out MyType mytypeobject, string strtype) // this method takes 2 arguments: 1-st for the object you want to instantiate and the second one for type name.
{
MyType sys = null;
mytypeobject = null;
string fullname = _asmName+strtype;
try {
ObjectHandle handle = System.Activator.CreateInstance(_asmName, fullname); //this method takes assembly name and type name to create an instance of the object
MyType sys = (MyType)handle.Unwrap(); //You need to cast it to particular kind of the object
}
catch
{
throw new ApplicationException("Worker Factory can not create and object from assembly "+_asmName+" with name "+ns+".");
}
finally
{
if(sys != null) mytypeobject = sys;
}
}
}
}