在哪里可以在实现相同接口的多个类中放置所需的通用逻辑?

App*_*lus 3 c# inheritance

给出以下界面:

public interface IFoo
{
    bool Foo(Person a, Person b);
}
Run Code Online (Sandbox Code Playgroud)

以及以上两种实现:

public class KungFoo : IFoo
{
    public bool Foo(Person a, Person b)
    {
        if (a.IsAmateur || b.IsAmateur) // common logic
          return true;
        return false;
    }
}

public class KongFoo : IFoo
{
    public bool Foo(Person a, Person b)
    {
        if (a.IsAmateur || b.IsAmateur) // common logic
          return false;
        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)

我应该在哪里放置"通用逻辑"(如代码中所述),因此它只在一个地方(例如作为Func)并且不需要为多个实现重复(如上所述)?

请注意,上面的示例非常简单,但现实生活中的"通用逻辑"更复杂,Foo()方法做了一些有用的事情!

我希望问题很清楚(在其他地方尚未得到解答 - 我确实进行了搜索)但如果需要,可以随时向我探讨更多细节.

Joe*_*ton 9

在一个常见的抽象类中:

public interface IFoo
{
    bool Foo(Person a, Person b);
}

public abstract class FooBase : IFoo
{
    public virtual bool Foo(Person a, Person b)
    {
        if (a.IsAmateur || b.IsAmateur) // common logic
          return true;
        return false;
    }
}

public class KungFoo : FooBase
{

}

public class KongFoo : FooBase
{
    public override bool Foo(Person a, Person b)
    {
        // Some other logic if the common logic doesn't work for you here
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 当然这是个人偏好,但是看到一个以'I'前缀命名的类通常是为接口保留的,这对我来说似乎不对.我喜欢抽象类的想法,但我放弃了'我'. (2认同)