如何重构2个略有不同的接口实现

时间:2018-02-15 17:34:07

标签: c# oop design-patterns

我有两个实现接口的类。正如您所看到的,接口方法Evaluate的实现在两个类中都非常相似,但变化很小。如何在这里分解出重复的代码

public class Policy1 : IPolicy
{
    private readonly IPolicy _innerPolicy1;
    private readonly IPolicy _innerPolicy2;

    public Task Evaluate(Input input)
    {
        _innerPolicy1.Evaluate(input);
        _innerPolicy2.Evaluate(input);

        return Task.FromResult(input);
    }
}

public class Policy2 : IPolicy
{
    private readonly IPolicy _innerPolicy1;
    private readonly IPolicy _innerPolicy2;
    private readonly IPermissionService _permissionService;

    public Task Evaluate(Input input)
    {
        _innerPolicy1.Evaluate(input);
        if (HasInnerPolicy2Permission(input))
        {
            _innerPolicy2.Evaluate(input);
        }

        return Task.FromResult(input);
    }

    private bool HasInnerPolicy2Permission(Input input)
    {
        return _permissionService.GetInnerPolicy2Permission(input);
    }
}

1 个答案:

答案 0 :(得分:1)

推导政策1&来自抽象类的Policy2实现根据您的Policy2类和&进行评估。有一个HasInnerPolicy2Permission的抽象方法 - Policy1只返回true,Policy2实现就像在该类中一样。

类似的东西:

public abstract class Policy : IPolicy
{
    protected readonly IPolicy _innerPolicy1;
    protected readonly IPolicy _innerPolicy2;

   public Task Evaluate(Input input)
    {
        _innerPolicy1.Evaluate(input);
        if (HasInnerPolicy2Permission(input))
        {
            _innerPolicy2.Evaluate(input);
        }

        return Task.FromResult(input);
    }

    protected abstract bool HasInnerPolicy2Permission(Input input);
}

public class Policy1 : Policy
{
    protected override bool HasInnerPolicy2Permission(Input input)
    {
        return true;
    }
}

public class Policy2 : Policy
{
    private readonly IPermissionService _permissionService;
    protected override bool HasInnerPolicy2Permission(Input input)
    {
        return _permissionService.GetInnerPolicy2Permission(input);
    }
}

如果您认为可能有一个具有显着不同的Evaluate函数的Policy3类,那么您可以将原始版本设置为虚拟。