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

给定以下界面:

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

以及以上两种实现:

 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; } } 

我应该在哪里放置“通用逻辑”(如代码中所述),因此它只在一个地方(例如作为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 } } 

您可以将基类用于常用方法,但可以使用规范模式相当整齐地外化您的公共逻辑(或业务规则)。

那里有很多罗嗦的例子和白皮书,如果你对这些东西没问题(我发现它有点过于学术性),请仔细阅读它们,但似乎有一个很好的介绍:

http://devlicio.us/blogs/jeff_perrin/archive/2006/12/13/the-specification-pattern.aspx

  • 您可以实现一个由所有适当的类inheritance的类,并将该function作为protected方法提供。

  • 最好你可以实现一个扩展方法 ,我更喜欢它,因为它不会限制你在某个inheritance层次结构中使用这个逻辑,而是允许你在共享类型或接口的所有类中使用它。

我会使用这样的抽象基类:

 public interface IFoo { bool Foo(Person a, Person b); } public class KungFoo : FooImpl { public override bool Foo(Person a, Person b) { if (this.IsAmateur(a, b)) return true; return false; } } public class KongFoo : FooImpl { public override bool Foo(Person a, Person b) { if (this.IsAmateur(a, b)) return false; return true; } } public abstract class FooImpl : IFoo { public abstract bool Foo(Person a, Person b); protected readonly Func IsAmateur = (a, b) => a.IsAmateur || b.IsAmateur; } public class Person { public bool IsAmateur { get; set; } } 

我不是ac #developer但我要说你必须将父类更改为实际的类并在其中实现该方法,当然如果你想添加其他未实现的方法,你会声明一个抽象类,但是这就是它的样子;

 public abstract class IFoo{ bool Foo(Person a, Person b){ if (a.IsAmateur || b.IsAmateur) // common logic return true; } public abstract Object otherFooMethod(Object o); } 

然后在你的子课程中,你会像这样使用它:

 public class KungFoo : IFoo{ //Foo already implemented public Object otherFooMethod(Object o){ return o; } } public class KongFoo : IFoo { public bool Foo(Person a, Person b) { if (a.IsAmateur || b.IsAmateur) // common logic return false; return !base.Foo(); } public Object otherFooMethod(Object o){ return o; } }