|
using System;
using System.Collections;
namespace Objects
{
/// <summary>
/// Summary description for ObjectFactory.
/// </summary>
public class ObjectFactory
{
#region Static
/// <summary>
/// Register handler functions to create new types of objects.
/// </summary>
/// <param name="type">The type of the object.</param>
/// <param name="creator">The handler function.</param>
/// <returns>true if successful.</returns>
public static bool RegisterHandler(Int32 type, ObjectCreator creator)
{
bool res = false;
try
{
if (m_handlers[type] != null)
return false;
// insert the handler to the table according to the type.
m_handlers[type] = creator;
res = true;
}
catch(Exception ex)
{
Console.WriteLine("Can't register handler - "+ex.Message);
}
return res;
}
/// <summary>
/// Unregister handler functions according to type.
/// </summary>
/// <param name="type">The type of the object.</param>
/// <returns>true if successful.</returns>
public static bool UnregisterHandler(Int32 type)
{
bool res = true;
try
{
if (m_handlers[type] == null)
return res;
// remove the handler to the table according to the type.
m_handlers[type] = null;
GC.Collect();
}
catch(Exception ex)
{
Console.WriteLine("Can't unregister handler - "+ex.Message);
res = false;
}
return res;
}
/// <summary>
/// This is the static method that creates all types of objects.
/// </summary>
/// <remarks>Factory method.</remarks>
/// <param name="type">The key of objects to create.</param>
/// <param name="list">The parameter list for the object.</param>
/// <returns>An object.</returns>
public static AObject CreateObject(Int32 type, params object [] list)
{
AObject aobject = null;
try
{
// get the handler that creates the objects
ObjectCreator creator = (ObjectCreator)m_handlers[type];
// create the object with the handler.
if (creator != null)
aobject = creator(list);
}
catch(Exception ex)
{
Console.WriteLine("Can't get object from handler - "+ex.Message);
}
return aobject;
}
#endregion
#region Protected
/// <summary> A table holding the handlers for creating objects. </summary>
protected static Hashtable m_handlers = new Hashtable();
#endregion
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
Software designer and programmer.
Programming languages:
MFC, C++, Java , C#, VB and sometimes C and assembly.