工厂方法还是其他模式?
我有一个任务实体,需要根据任务类型进行解析。我会将特定类型任务的逻辑封装在一个类中,但是将类型与实现解析逻辑的类相匹配的普遍接受的方法是什么?
我的第一个冲动是做一个工厂,例如:
TaskResolverFactory.GetForType(TaskType) // returns IsATaskResolver, which has a Resolve method
可能在工厂内部,一个案例声明或其他东西。
另一个想法是使用像 StructureMap
这样的东西,但我认为这对于这种情况来说是多余的 - 你同意吗?
我还缺少哪些其他方法,以及替换大型 Case/Switch 语句的普遍接受的方法是什么?
I have a Task entity that needs to be Resolved based on the type of Task it is. I would encapsulate the logic for a specific type of Task in a class, but what is the generally accepted way to match the type with the class that implements the Resolving logic?
My first impulse is to do a Factory, like:
TaskResolverFactory.GetForType(TaskType) // returns IsATaskResolver, which has a Resolve method
Probably inside the Factory, a Case statement or something.
Another thought is to use something like StructureMap
, but I think that is overkill for this situation - do you agree?
What other methods am I missing, and what is the generally accepted method for replacing a big Case/Switch statement?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你是对的 -
Factory
是这个问题的经典模式。如果这是您需要进行此类解析的唯一地方(并且逻辑很简单),我同意 -
StructureMap
是过度杀伤力。You are right - a
Factory
is the classic pattern for this issue.If this is the only place you need to do such resolution (and the logic is simple), I agree -
StructureMap
is overkill.你可能会考虑这样的事情:
You might consider something like this:
工厂是一条出路。
至于大 switch 语句,您的其他选项包括:
我认为反射路由是最容易维护的,但是当您还没有类型时(假设您的“类型”是
类型
)。既然你已经有了类型,剩下的就很简单了:
A factory is the way to go.
As for the big switch statement, your other options include:
I think the reflection route is the easiest to maintain but the complexity arises when you don't already have the type (assuming your "type" is a
Type
).Since you already have the type, the rest is real easy: