工厂模式:确定具体的工厂类实例化?

时间:2010-06-05 22:13:45

标签: c# design-patterns factory

我正在尝试学习模式,而且我一直在确定工厂模式如何或在何处确定要实现的类。如果我有一个调用工厂并发送它的应用程序,比如一个xml配置文件来确定要采取什么类型的操作,那么解释配置文件的逻辑会在哪里发生?

工厂

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");
        }
    }
}

1 个答案:

答案 0 :(得分:3)

实例化的实际工厂在运行时选择,通常由单独的工厂加载程序类选择。加载器可以获得必要的配置,例如,在xml配置文件中,从中读取要加载的具体工厂的类名。

这本身并不是一个非常复杂的逻辑;将它放入工厂装载程序类的原因是可重用性。您的应用程序中可以有许多工厂,并且通常,大多数工厂加载代码非常相似,因此将其放入单独的类(层次结构)可以消除代码重复。当然,逻辑可能与此示例不同且更复杂。

E.g。更动态的方案是在xml文件中指定按钮/菜单项和类名之间的映射,然后在GUI上,用户可以通过按下按钮/选择菜单项来更改要使用的工厂。