给出以下界面:
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()方法做了一些有用的事情!
我希望问题很清楚(在其他地方尚未得到解答 - 我确实进行了搜索)但如果需要,可以随时向我探讨更多细节.
在一个常见的抽象类中:
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)