您如何决定使用抽象类和接口? [英] How do you decide between using an Abstract Class and an Interface?

查看:33
本文介绍了您如何决定使用抽象类和接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

重复:接口与基类

我一直在深入了解 OOP、设计模式和 actionscript 3 的世界,但我仍然很好奇如何知道何时使用抽象类(不支持抽象类的 AS3 的伪类)和接口.对我来说,两者都只是作为模板,确保在给定的类中实现某些方法.区别仅仅在于抽象类需要继承而接口只是扩展吗?

I have been getting deeper into the world of OOP, design patterns, and actionscript 3 and I am still curious how to know when to use an Abstract class (pseudo for AS3 which doesn't support Abstract classes) and an interface. To me both just serve as templates that make sure certain methods are implemented in a given class. Is the difference solely in the fact that Abstract classes require inheritance and an Interface merely extends?

谢谢,布赖恩·霍奇hodgedev.com

推荐答案

如果您希望它的子类具有某些功能,请使用抽象类.例如,如果您有一组函数,您希望所有基本抽象类的子类都具有这些函数.

Use an abstract class if you have some functionality that you want it's subclasses to have. For instance, if you have a set of functions that you want all of the base abstract class's subclasses to have.

如果您只想要关于行为/功能的一般契约,请使用接口.如果您有一个函数或对象想要接收一组不同的对象,请使用接口.然后就可以把传入的对象改掉了,而不用改变取它的方法或对象.

Use an interface if you just want a general contract on behavior/functionality. If you have a function or object that you want to take in a set of different objects, use an interface. Then you can change out the object that is passed in, without changing the method or object that is taking it.

与抽象类相比,接口通常是松散的.在不断为接口的所有方法编写相同代码的情况下,您不希望使用接口.使用抽象类并定义每个方法一次.

Interfaces are typically loose, compared to Abstract classes. You wouldn't want to use interfaces in a situation where you are constantly writing the same code for all of the interface's methods. Use an abstract class and define each method once.

此外,如果您尝试创建特定的对象继承层次结构,您真的不想尝试仅使用接口来实现.

Also, if you are trying to create a specific object inheritance hierarchy, you really wouldn't want to try to do that with just interfaces.

同样,在某些语言中,你只能有一个基类,如果一个对象已经有一个基类,你将不得不进行一些重构才能使用抽象基类.这可能意味着也可能不意味着您可能想改用界面.

Also, again, in some languages you can only have a single base class, and if an object already has a base class, you are going to have to do some refactoring in order to use an abstract base class. This may or may not mean that you might want to use an inteface instead.

正如@tvanfosson 所指出的,使用大量接口并不是一个坏主意,当您真正理解抽象类和接口时,这并不是真正的非此即彼的情况.特定情况可以同时使用抽象类和接口,也可以都不使用.有时我喜欢使用接口来限制方法或对象在传入的参数对象上可以访问的内容.

As @tvanfosson notes, it's not a bad idea to use a lot of interfaces, when you really understand abstract classes and interfaces, it's not really an either/or situation. A particular situation could use both abstract classes and interfaces or neither. I like to use interfaces sometimes simply to restrict what a method or object can access on a passed in parameter object.

这篇关于您如何决定使用抽象类和接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆