【问题标题】:Any better approach to tackle this simple business use case?有没有更好的方法来处理这个简单的业务用例?
【发布时间】:2023-03-07 04:18:01
【问题描述】:

我有如下界面:

public interface IValidator
{
    // Checks whether the selected roles are Valid based on Buisness rules for the 
    // specific EntityValidator
    bool HasCompleteValidSelection(
        ICollection<Role> availableRoles, ICollection<Role> selectedRoles);        
    //Checks whether the available roles are Valid for the specific entity 
    bool HasValidRoles(ICollection<Role> availableRolesList);
    //Computes the Remaining Roles that needs to be selected to make it a Valid selection
    ICollection<Role> GetRemainingRoles(
        ICollection<Role> availableRoles, ICollection<Role> selectedRoles);
}

现在,我有一堆 EntityType,在枚举中提到:

public enum EntityType
{        
    Shop= 1,
    SmallBuisness= 2,
    Corporation = 3,
    Firm = 4,
    Partnership = 5,
    Unknown = 0
}

上述所有实体类型都有其对应的验证器类,这些验证器类实现了 IValidator。

public class ShopValidator : IValidator
{
    public bool HasCompleteValidSelection(
        ICollection<Role> availableRoles, ICollection<Role> selectedRoles)
    { /*implementation */ }
    public bool HasValidRoles(ICollection<Role> availableRolesList)
    { /*implementation */ }
    public ICollection<Role> GetRemainingRoles(
        ICollection<Role> availableRoles, ICollection<Role> selectedRoles)
    { /*implementation */ }
}

但令人担忧的是,一些验证器类具有完全相同的逻辑/代码。 我想到的是:

  1. 代替接口,创建抽象类并保持通用 代码在那里
  2. 具有不同实现的验证器类是 覆盖抽象类。

现在,我的问题是:

  1. 虽然上述工作正常,有没有更好的 更适合上述场景的方法/设计模式?
  2. 我正在使用如下所示的 Autofac,它工作正常,但是有没有 您可以预见的问题?

    builder.RegisterType().As().Keyed(EntityType.Shop);

    // 其他验证器类似。

【问题讨论】:

    标签: c# design-patterns dependency-injection autofac


    【解决方案1】:

    就我个人而言,我喜欢你最初的提议。有些人可能不同意,但我喜欢为每个实体类型创建一个类的对称性,即使其中一些类没有代码。

    也就是说,如果有一些通用代码,我会使用您将接口转换为基类的建议并将您的通用代码放在那里。 (很像 CException。)

    当然,如果通用代码更复杂,那么您可能有更专业的基类,您的最终类可以从中派生,但在这种情况下,它就没有那么优雅了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-24
      • 2013-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多