有什么更好的方法来解决这个简单的业务用例?

时间:2018-10-03 02:09:46

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

我有以下界面:

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. 具有不同实现的
  3. Validator类是 覆盖抽象类。

现在,我的问题是:

  1. 尽管上面的方法工作正常,但是还有什么更好的方法吗? 方法/设计模式更适合上述情况?
  2. 我正在像下面那样使用Autofac,它的工作正常,但是有没有 您可以预见的问题?

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

    //其他验证器。

1 个答案:

答案 0 :(得分:0)

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

也就是说,如果有一些通用代码,我会建议您将接口转换为基类,然后将通用代码放在那里。 (非常类似于CException。)

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