需要一个设计模式来删除对象创建中的枚举和切换语句 [英] Need a design pattern to remove enums and switch statement in object creation
问题描述
所以我首先创建一个基础类:
public abstract class Position
{
public abstract string Name
{
get;
}
}
和子类...
public class Defender:Position
{
public override string Name
{
get {return卫士; }
}
}
等等。这是很好的。
但现在我需要一个函数来创建这些对象。我需要通过位置函数创建。所以一个可能的解决方案是创建一个所有位置的枚举,并将该值传递给一个打开枚举并返回相应对象的函数。但这会触发我的代码气味报警。这个soultion将一个函数中的类,枚举和开关连接在一起:
public static Position GetByType(Types position)
{
switch(position)
{
case Types.Defender:
return new Defender();
...还有可怕的代码
我应该查看什么解决方案?这是哪种设计模式?
如果你必须小规模地做到这一点,交换机不是很糟糕,特别是如果它居住在一个地方。
如果你必须在中等规模的情况下,你可能想考虑改进内部的一些 - Steve Ellinger的建议是一个合理的。我个人喜欢使用 IDictionary< MyEnum,Action< T>
其中Action返回有问题的类的新实例。
如果您必须以大规模或可配置的规模执行此操作,您应该可以查看一个IoC控制器,如结构图或ninject或任何酷的孩子们玩这些天。
Let's say I am creating a sports game, and in this game there are various positions a player can play, attack, defence, etc. So I start by creating a base class:
public abstract class Position
{
public abstract string Name
{
get;
}
}
and the subclasses...
public class Defender : Position
{
public override string Name
{
get { return "Defender"; }
}
}
and so on. This is all fine.
But now I need a function to create these objects. I need a create by position function. So one possible solution is to create an enum of all the positions and pass this value to a function that switches on the enum and returns the appropriate object. But this triggers my code smell alarm. This soultion ties together the classes, the enum and the switch inside a function:
public static Position GetByType(Types position)
{
switch(position)
{
case Types.Defender:
return new Defender();
... and further terrible code
What solution should I be looking at? Which design pattern is this?
If you have to do this on a small scale, the switch isn't really bad, especially if it lives in a single place.
If you have to do this on a medium scale, you might want to consider improving the internals a bit -- Steve Ellinger's suggestion is a reasonable one. Personally I prefer to use a IDictionary<MyEnum, Action<T>>
where the Action returns a new instance of the class in question.
If you have to do this on a grand or configurable scale, you should probably check out an IoC controller such as structuremap or ninject or whatever the cool kids are playing with these days.
这篇关于需要一个设计模式来删除对象创建中的枚举和切换语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!