抽象基类和接口有很多类似的地方,那么我们在软件架构的过程中如何决定该用抽象基类还是接口呢?Stack Overfollow上有一个回答总结得比较好,虽然只有短短几十个字:
Abstract classes and interfaces are semantically different, although their usage can overlap. An abstract class is generally used as a building basis for similar classes. Implementation that is common for the classes can be in the abstract class. An interface is generally used to specify an ability for classes, where the classes doesn't have to be very similar.
可以这么理解:基类是爹,接口是能力。爹只能有一个,而且他决定了你是什么,但能力可以有多个。
应该考虑使用抽象基类的场景:
- 逻辑上是同一类的东西(is a...);
- 有需要实现的公共方法或属性;
- 需要序列化的成员类型(因为接口无法序列化);
阅读:143