1

我有一个抽象基类,其中有许多继承的类。我想做的是一个静态成员接受一个字符串,第一个可以解析字符串的类(只有一个继承的类应该能够)并返回继承类的实例。

这就是我目前正在做的事情。

public static Epl2Command GenerateCommandFromText(string command)
{
    lock (GenerateCommandFromTextSyncRoot)
    {
        if (!Init)
        {
            Assembly a = Assembly.GetAssembly(typeof(Epl2Command));
            Types = new List<Type>(a.GetTypes());
            Types = Types.FindAll(b => b.IsSubclassOf(typeof(Epl2Command)));
            Init = true;
        }
    }
    Epl2Command ret = null;
    foreach (Type t in Types)
    {

        MethodInfo method = t.GetMethod("GenerateCommand", BindingFlags.Static | BindingFlags.Public);

        if (method != null)
            ret = (Epl2Command)method.Invoke(null, new object[] { command });
        if (ret != null)
            break;
    }
    return ret;
}

我想要它,这样我的代码会检查所有继承的类,而不会让未来的程序员在添加更多继承的类时回来编辑这个函数。

有没有办法可以强制继承的类实现自己的GenerateCommand(string)

public static abstract Epl2Command GenerateCommand(string command)不是有效的 C#。或者当我应该使用锤子时,我是在用鞋钉钉子吗?做这个类工厂的任何更好的方法将不胜感激。

4

2 回答 2

1

C# 不支持静态接口,因此您不能定义静态构建器方法,例如

public interface ICommand
{
    static ICommand CreateCommand(string command);
}

我同意凯文的观点,你需要一个工厂模式。我会更进一步说您也需要每个命令类型的构建器。像这样

public interface ICommandBuilder
{
    bool CanParse(string input);
    ICommand Build(string input);
}

public interface ICommandBuilder<TCommand> : ICommandBuilder 
    where TCommand : ICommand
{
    TCommand Build(string input);
}

然后您的工厂可以接受任何输入命令字符串,查询所有构建器是否可以解析该字符串,然后在可以解析的那个上运行构建。

public interface ICommandFactory
{
    ICommand Build(string input);
}

public class CommandFactory
{
    public ICommand Build(string input)
    {
        var builder = container.ResolveAll(typeof(ICommandBuilder))
            .First(x => x.CanParse(input));
        return builder.Build(input);
    }
}
于 2010-04-14T14:46:54.107 回答
0

你逃避的是工厂方法:

http://www.dofactory.com/Patterns/PatternFactory.aspx

这是一个如何实现它的链接。

于 2010-04-14T13:37:42.497 回答