views:

153

answers:

1

I'm trying to learn patterns and I'm stuck on determining how or where a Factory Pattern determines what class to instanciate. If I have a Application that calls the factory and sends it, say, an xml config file to determine what type of action to take, where does that logic for interpreting the config file happen?

THE FACTORY

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace myNamespace
{
    public abstract class SourceFactory
    {
        abstract public UploadSource getUploadSource();
    }
    public class TextSourceFactory : SourceFactory
    {
        public override UploadSource getUploadSource()
        {
            return new TextUploadSource();
        }
    }
    public class XmlSourceFacotry : SourceFactory
    {
        public override UploadSource getUploadSource()
        {
            return new XmlUploadSource();
        }
    }
    public class SqlSourceFactory : SourceFactory
    {
        public override UploadSource getUploadSource()
        {
            return new SqlUploadSource();
        }
    }
}

THE CLASSES

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace myNamespace
{
    public abstract class UploadSource
    {
        abstract public void Execute();
    }
    public class TextUploadSource : UploadSource
    {
        public override void Execute()
        {
            Console.WriteLine("You executed a text upload source");
        }
    }
    public class XmlUploadSource : UploadSource
    {
        public override void Execute()
        {
            Console.WriteLine("You executed an XML upload source");
        }
    }
    public class SqlUploadSource : UploadSource
    {
        public override void Execute()
        {
            Console.WriteLine("You executed a SQL upload source");
        }
    }
}
+2  A: 

The actual factory to instantiate is selected at runtime, often by a separate factory loader class. The loader may get the necessary configuration, e.g. in an xml config file, and read from it the class name of the concrete factory to load.

This in itself is not a very complicated logic; the reason to put it into a factory loader class is reusability. You can have many factories in your app, and often, most of the factory loading code is pretty similar, so putting it into a separate class (hierarchy) eliminates code duplication. And of course, the logic may be different and more complicated than this example.

E.g. a more dynamic scenario would be to specify a mapping between buttons / menu items and class names in the xml file, then on the GUI, the user could change the factory to be used by pressing a button / selecting a menu item.

Péter Török