Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Delegate Factory

0.00/5 (No votes)
11 Jan 2005 1  
A dynamic factory using delegates

Introduction

The target of this article is to show another factory implementation using delegates. I've searched CodeProject for a similar implementation and though some are close, they're not quite the same. So I've decided to post this factory which I use in my current project.

This article does not aim at explaining the whole concept of factory or why you would use that particular design pattern.

Table of Contents

Goals

The goals in writing this factory are as follows:

  1. Dynamic factory - It will be possible in the future to use the same factory for new types of objects without opening the factory's code.
  2. Creation responsibility - The factory should not know how to create the objects.
  3. Ease of use.

Using a Delegate

Using delegates will help us achieve goals 1 and 2, it might set us on a collision course with goal 3 but we'll see.

The declaration of the delegate looks like this:

/// <SUMMARY>
/// A handler function for the factory to create objects;
/// </SUMMARY>

public delegate AObject ObjectCreator(params object [] list);

This delegate will help us obscure the way objects are created from the factory and help us register delegates of this type on the factory.

Implementing the Object Hierarchy

The factory will create our first usable object in our tree, so that we don't have to downcast straight away (only if it's really needed).

The base class is abstract and defines one variable member and one abstract function:

/// <SUMMARY>
/// Summary description for AObject.
/// </SUMMARY>

public abstract class AObject
{
    #region Override

    /// <SUMMARY>
    /// Force all descendents to implement.
    /// </SUMMARY>

    public abstract void Print();

    #endregion

    #region protected

    /// <SUMMARY>Some variable to play with.</SUMMARY>

    protected Int32 m_nType;

    #endregion
}

The derived classes look like this:

/// <SUMMARY>
/// Summary description for Class1.
/// </SUMMARY>

public class Class1 : AObject
{
    #region Constants

    /// <SUMMARY>
    /// The class type identifier.
    /// </SUMMARY>

    public const Int32 ClassType = 1;

    #endregion
        
    #region C'tor

    /// <SUMMARY>
    /// Default C'tor.
    /// </SUMMARY>

    internal Class1()
    {
        this.m_nType = ClassType;
    }

    #endregion

    #region Overrides

    /// <SUMMARY>
    /// Implementation of Print.
    /// </SUMMARY>

    public override void Print()
    {
        String msg = String.Format("Class: {0, 20} Value: {1, 10}",
                                          ToString(), m_nType*67);
        Console.WriteLine(msg);
    }

    #endregion

    #region Static

    /// <SUMMARY>
    /// A handler function for the factory to create objects;
    /// </SUMMARY>

    /// The parameter list.
    /// <RETURNS>A Class1 object.</RETURNS>

    public static AObject ObjectCreator(params object[] list)
    {
        return new Class1();
    }

    #endregion
}

As you can see, we implemented a Print function for the derived that does something (hopefully something different than other derived) and we've added a static function that creates a new object of Class1.

The static function ObjectCreator keeps the responsibility of creating objects within the class.

The Factory

The factory class maps the classes' static functions, with the help of a delegate to the type that we wish to create.

The map is done through a hashtable with the type of the object being the key and the delegate that encapsulates a static function as the value.

The factory:

/// <SUMMARY>
/// Summary description for ObjectFactory.
/// </SUMMARY>

public class ObjectFactory
{
    #region Static

    /// <SUMMARY>
    /// Register handler functions to create new types of objects.
    /// </SUMMARY>

    /// The type of the object.
    /// The handler function.
    /// <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>

    /// The type of the object.
    /// <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>

    /// The key of objects to create.
    /// The parameter list for the object.
    /// <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
}

Notice that the factory has register and unregister functions, later on, we'll see how to use them.

  • RegisterHandler - The register function that takes a delegate and inserts it to the hashtable with the class identifier as the key.
  • UnregisterHandler - The unregister function takes the type and removes whatever delegate was there as the value.
  • CreateObject - The function that creates objects according to their type (key). This function extracts a delegate from the hashtable from position type and invokes the delegate (calls the static function of the object that we've registered before).

Using the Factory

After comments from numerous esteemed colleagues, I changed the following code a bit, so it's more obvious that the factory doesn't "know" what type it's getting, but rather checks to see if it knows how to create an object with the provided key (type).

static void Main(string[] args)
{
    try
    {
        // registering the types that the factory will create
        ObjectFactory.RegisterHandler(Class1.ClassType, 
                new ObjectCreator(Class1.ObjectCreator));
        ObjectFactory.RegisterHandler(Class2.ClassType, 
                new ObjectCreator(Class2.ObjectCreator));
        ObjectFactory.RegisterHandler(Class3.ClassType, 
                new ObjectCreator(Class3.ObjectCreator));

        AObject aobject = null;
        // creating the objects
        for (int i = 0; i<100; i++)
        {
                aobject = ObjectFactory.CreateObject(i%3+1, null);
                aobject.Print();
        }
        // unregistering a type
        if (!ObjectFactory.UnregisterHandler(Class1.ClassType))
            Console.WriteLine("Really ?!");

        // trying to create an unregistered type
        aobject = ObjectFactory.CreateObject(Class1.ClassType, null);
        if (aobject != null)
            aobject.Print();
        else
            Console.WriteLine("aobject is null");
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
    Console.ReadLine();
}

Notice the registration process:

We pass a type to be registered and we create a new delegate passing it the static function of the type that we're registering. We have to make sure that types are registered before we can use the factory to create objects, so the registration process should be as soon as possible in the program.

One more thing to notice is that Class3 (if you've downloaded the code, you may have noticed already) belongs to the same namespace (and assembly) as Main and not to the namespace (and assembly) that the rest of the classes belong to. This means that we have achieved goal 1 and goal 2.

I leave it up to you to decide if goal 3 was achieved.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here