Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 工厂模式来实例化工厂类中的类_C#_Pattern Matching_Factory_Factory Pattern - Fatal编程技术网

C# 工厂模式来实例化工厂类中的类

C# 工厂模式来实例化工厂类中的类,c#,pattern-matching,factory,factory-pattern,C#,Pattern Matching,Factory,Factory Pattern,我有一个工厂类,在那里我根据字符串匹配实例化类 示例代码段: class Factory { Dictionary test = new Dictionary(string, ICreate); public FactoryMethod() { test.Add("classA",new a()); test.Add("classB",new b()); test.Add("classC",new c());

我有一个工厂类,在那里我根据字符串匹配实例化类

示例代码段:

class Factory
{
     Dictionary test = new Dictionary(string, ICreate);

     public FactoryMethod()
     {
        test.Add("classA",new a());
        test.Add("classB",new b());
        test.Add("classC",new c());
     }

     public ICreate Create(string toMatch)
     {
        return test[toMatch];  
     }
}
但是现在我想匹配一些模式(文件路径),然后根据匹配的模式实例化类

所以我的问题是,我在哪里可以存储这些我想要匹配的模式?
它们应该在我的数据库中的“表”中,还是我可以在这里有一个哈希表(当任何一个模式匹配时,该哈希表映射到一个要进行Intantate的类)

首先,您的
Create
方法实际上并没有创建任何内容。它返回一个已经创建的实例。每次调用
Create
都将返回相同的实例

如果这是你想要的,好吧,但是如果你每次都想要一个新的实例,我可以提个建议吗?存储返回新对象的函数,而不是存储对象:

class Factory
{
     Dictionary<string,Func<ICreate>> test = new Dictionary<string,Func<ICreate>>();

     public Factory()
     {
        test.Add( "classA", () => new a() );
        test.Add( "classB", () => new b() );
        test.Add( "classC", () => new c() );
     }

     public ICreate Create(string toMatch)
     {
        var creationFunction = test[toMatch];
        return creationFunction();
     }
}
输出:

You just created an instance of 'a'.


在本例中,我们使用
Contains()
进行了模式匹配,但由于它是Func,因此您可以使用任何字符串函数、正则表达式编写您想要的任何表达式,您可以命名它。你也可以混搭;例如,可以使用正则表达式来标识需要ClassA的模式,但可以使用正则比较来标识ClassB的模式。此外,如果您希望确保提交的任何字符串都匹配一个且仅匹配一个模式,我们可以将LINQ函数从
First
更改为
Single

而不是硬编码实例化-使用依赖性注入。配置中可能有模式vs类型的字典。这样你将来可以管理/发展工厂。谢谢你,约翰。谢谢你建议的更正,也谢谢lamda的表达。
You just created an instance of 'a'.