我有一个 IComposer
我的 C# 项目中的界面:
public interface IComposer
{
string GenerateSnippet(CodeTree tree);
}
CodeTree
是一个包含 List<CodeTree>
的基类从 CodeTree
继承的类.例如:
public class VariablesDecleration : CodeTree
{
//Impl
}
public class LoopsDecleration : CodeTree
{
//Impl
}
我可以有几个实现 IComposer
的类在每一个中我都有 GenerateSnippet
遍历 List<CodeTree>
基本上做:
foreach (CodeTree code in tree.Codes)
{
if (code.GetType() == typeof(VariablesDecleration))
{
VariablesDecleration codeVariablesDecleration = (VariablesDecleration) code;
// do class related stuff that has to do with VariablesDecleration
}
else if (code.GetType() == typeof(LoopsDecleration))
{
LoopsDecleration codeLoopsDecleration = (LoopsDecleration) code;
// do class related stuff that has to do with LoopsDecleration
}
}
我有这个foreach
和 if
在实现 IComposer
的每个类中重复的语句.
我想知道是否有更好的设计模式来处理这种情况。让我们说明天我添加一个继承自 CodeTree
的新类- 我将不得不检查所有实现 IComposer
的类并修改它们。
我在考虑访问者设计模式 - 但不确定,也不完全确定是否以及如何实现它。对于这种情况,Visitor 是否是正确的解决方案?
最佳答案
在VariablesDecleration
和LoopsDecleration
中移动与特定类相关的实现,在CodeTree
中提供抽象实现。然后在您的循环中,在 CodeTree 中简单调用该方法,无需 if...else 检查。
public class VariablesDecleration : CodeTree
{
//Impl
public void SomeStuff()
{
//... specific to Variables
}
}
public class LoopsDecleration : CodeTree
{
//Impl
public void SomeStuff()
{
//... specific to Loops
}
}
public class CodeTree : ICodeTree
{
void SomeStuff();
}
foreach (CodeTree code in tree.Codes)
{
code.SomeStuff();
}
根据评论,您可能需要这样的东西:
public interface IComposer
{
string DoStuff();
}
public class LoopComposer1 : IComposer
{
string DoStuff(){ .. }
}
public class VariableComposer1 : IComposer
{
string DoStuff(){ .. }
}
public class ComposerCollection
{
private IEnumerable<IComposer> composers;
string GenerateSnippet()
{
foreach(var composer in composers)
{
composer.DoStuff();
}
...
...
}
}
当然,现在关系倒过来了,你的代码树或者它的创建者必须为它定义 Composer 集合。
关于c# - 接口(interface)实现中多个 if 语句的最佳设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34389854/