继承设计采用接口+抽象类。好的做法呢? [英] Inheritance design using Interface + abstract class. Good practice?
问题描述
我真的不知道如何标题这个问题,但基本上我有一个这样的接口:
I'm not really sure how to title this question but basically I have an interface like this:
public interface IFoo
{
string ToCMD();
}
一对夫妇它们实现的IFoo像absract类:
a couple of absract classes which implement IFoo like:
public abstract class Foo : IFoo
{
public abstract string ToCMD();
}
public abstract class Bar : IFoo
{
public abstract string ToCMD();
}
然后它继承Foo和酒吧类:
then classes which inherit Foo and Bar:
public class FooClass1 : Foo
{
public override string ToCMD()
{return "Test";}
} ///there are about 10 foo classes.
public class BarClass : Bar
{
public override string ToCMD()
{return "BarClass";}
} ///about the same for bar classes.
我这样做,这样,当我有喜欢我的自定义列表:
I am doing this so that when I have my custom list like:
public class Store<T> : List<T> where T : IFoo {}
然后我可以限制进入,但通过让接口类型。它仍然会采取任何类型的IFoo的
I then can restrict the types that go in it but by having the interface it will still take any type of IFoo.
是这样的:
Store<Foo> store = new Store<Foo>(); //Only Foo types will work.
store.Add(new FooClass1()); //Will compile.
Store<IFoo> store = new Store<IFoo>(); //All IFoo types will work.
store.Add(new FooClass1()); //Will compile.
store.Add(new BarClass()); //Will compile.
我的问题是:这是要对这个一个确定的方法吗?还是有更好的办法
My question is: Is this an ok way of going about this? or is there a better way?
编辑:图片 - >
Picture->
推荐答案
需要一个继承链是有问题的,一般。
The need for an inheritance chain is questionable, in general.
不过一个抽象基类的接口相结合的具体情况。我看这种方式:
However the specific scenario of combining an abstract base class with an interface.. I see it this way:
如果你有一个抽象基类这样,你也应该有一个相应的接口。如果你有一个接口,则使用抽象基类只有在继承链是明智的。
If you have an abstract base class like this, you should also have a corresponding interface. If you have an interface, then use the abstract base class only where the inheritance chain is sensible.
这就是说,如果我正在写一个库,这是一部分我的API /框架,我通常会包括可以作为基类的默认的实现。这将实施一个天真的,一般的方式,在可能情况下,接口的方法,离开需要继承来实现/重写的其余部分。
That said, if I'm writing a library and this is part of my API/Framework, I will generally include a "default implementation" that can be used as a base class. It will implement the interface methods in a naive, general way, where possible, and leave the rest for inheritors to implement/override as needed.
这仅仅是一个方便的特性库虽然,以协助谁想要通过提供可覆盖大多数他们需要已经实现什么功能例实现接口人
This is just a convenience feature of the library though, to assist people who want to implement the interface by providing a functional example that may cover most of what they need to implement already.
在总之,界面比基类更有价值,而是一个基类可能会节省大量的时间,降低马车接口实现。
In short, the interface is more valuable than the base class, but a base class might save a lot of time and reduce buggy interface implementations.
这篇关于继承设计采用接口+抽象类。好的做法呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!