避免在工厂类中使用多个if-else语句[与语言无关] [英] Avoid multiple if-else statements in a factory class [language agnostic]
问题描述
我有一些要筛选的数据,我想不出一个聪明的方法。假设我有3种类型:
I have some data that I'm trying to sift through and I can't figure out a smart way of doing this. Let's say I have 3 types:
A,B,C,它们都扩展了类S。
A, B, C and they all extend a class S.
如果我创建一个仅创建并返回类型为S的对象的工厂,那么这看起来将是非常程序化的。工厂在伪代码中的实现如下所示:
If I create a factory that just creates and returns and object of type S, it seems like it would be very procedural. The factory's implementation in pseudo-code would be something like this:
class Factory {
func create_obj(input_data) -> S {
if type(input_data) is A {
return A()
}
else if type(input_data) is B {
return B()
}
else {
return C()
}
}
}
现在,我可能有很多不同的数据类型。这意味着该算法在最坏的情况下处于二次时间。有没有更好的解决方案,设计模式或我可以查看的任何优化?更具体地说,我正在创建某些数据类型的实例,并且输入为文本行。
Now, I have a lot of different data types that it could possibly be. That means this algorithm in the worst case is in quadratic time. Is there a better solution, design pattern, or any optimizations I can look at? To be more specific, I'm creating instances of certain data types and the input is lines of text.
推荐答案
解决该问题的一种方法是使用预先填充的关联数组,其中键是字符串表示文件中的行/值,该值是应为该行返回的对象。
One way to approach the problem would be to use a pre-populated associative array where the key is a string representing a line/value in the file and the value is the object that should be returned for that line.
示例实现:
让文件
是一个关联数组。在启动时,工厂应使用 string 将该对象预填充到对象映射:
Let file
be an asscociateive array. On startup, the factory should pre-populate this array with string to object mappings :
files["A"] = new A();
files["B"] = new B();
files["C"] = new C();
然后可以给工厂传递一个 string ,它将在关联数组以获取相应的预填充对象:
The factory can then be passed a string which it will lookup in the associative array to fetch the corresponding pre-populated object :
func create_obj(input_data) -> S {
return files[input_data];
}
这篇关于避免在工厂类中使用多个if-else语句[与语言无关]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!