gpt4 book ai didi

excel - 重构 - 本例中使用哪种模式?

转载 作者:行者123 更新时间:2023-12-02 11:33:05 26 4
gpt4 key购买 nike

我有一个处理 Excel 文件中的行的函数。在这个函数中,我有一个 for 循环。现在,一旦提取一行,我们就会检查各种条件。如果任何条件为假,我们继续下一步row.可以使用模式使这段代码更加结构化吗?

 foreach (System.Data.DataRow dr in ds.Tables[0].Rows)
{

Product prod = GetProduct(dr);
if (prod == null)
{
IndicateNotInserted(dr, "InvalidProduct");
continue;
}



if (IsProductExpired())
{
IndicateNotInserted(dr, "Expired");
continue;
}
ProcessRow(dr);

最佳答案

您可以使用 chain of responsibility样式模式,其中有一系列类,每个类负责检查有效性的一个方面并报告错误类型。

您将把您的Prod传递给第一个类,该类将检查有效性,如果无效,它将报告并返回 false。如果它有效,它将返回当前实例的后继者的有效性检查(如果有的话)。

那么你的代码就可以获取Prod并将其传递给根有效性检查器,如果报告错误则继续。

这还可以让您将来轻松添加新的验证器,有可能无需重新编译即可完成此操作,具体取决于您如何实现验证器链的构建。

类似这样的东西:(伪代码,未测试/编译)

public interface IValidator
{
bool IsValid(Product product);
IValidator Successor{get;set;};
}

public class AbstractValidator : IValidator
{
IValidator m_successor=null;
public abstract bool IsValid(Product product);

IValidator Successor
{
get
{
if(m_sucessor==null)
return new AlwaysValidSuccessor();
else
return m_successor;
}
set
{
m_successor=value;
}
}
}

public class NullValidator : AbstractValidator
{
public bool IsValid(Product product)
{
if (product!=null)
{
return Successor.IsValid(product);
}
return false;
}
}

public class ExpiredValidator : AbstractValidator
{
public bool IsValid(Product product)
{
if (product.Expired==false) //whatever you need to do here
{
return Successor.IsValid(product);
}
return false;
}
}

然后你使用它:

IValidator validatorRoot = new NullValidator();
validatorRoot.Successor = new ExpiredValidator();
// construct the chain with as many as you need
//then use it
if (validatorRoot.IsValid(Prod)==false)
{
continue;
}

关于excel - 重构 - 本例中使用哪种模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3467061/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com