c# - 接口(interface)实现中多个 if 语句的最佳设计模式

标签 c# design-patterns visitor-pattern

我有一个 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
    }
}

我有这个foreachif在实现 IComposer 的每个类中重复的语句.

我想知道是否有更好的设计模式来处理这种情况。让我们说明天我添加一个继承自 CodeTree 的新类- 我将不得不检查所有实现 IComposer 的类并修改它们。

我在考虑访问者设计模式 - 但不确定,也不完全确定是否以及如何实现它。对于这种情况,Visitor 是否是正确的解决方案?

最佳答案

VariablesDeclerationLoopsDecleration中移动与特定类相关的实现,在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/

相关文章:

C# 在命中属性之前运行一段代码

c# - WPF ComboBox 绑定(bind) ItemsSource

design-patterns - Haskell IO 输出不正确

c# - Entity Framework 中首先从数据库更新模型的元数据不起作用

c# - 分隔后从较大的字符串创建字符串数组

将字符模式再现为数字模式

design-patterns - 为什么 Symfony EventDispatcher 对事件使用任意名称而不是基于类的传播?

oop - 访客模式的替代方案?

Java Jacc、AST 和递归访问者

具有可变返回类型的 C++ 访问者模式