简体   繁体   English

为什么要使用抽象类

[英]Why use abstract classes

I have been brushing up on the topic of advanced OOP and i find myself asking one question over and over... Why use abstract classes when all of the methods are defined in the child classes. 我一直在讨论高级OOP的主题,我发现自己一遍又一遍地问一个问题...当在子类中定义了所有方法时,为什么要使用抽象类。 Couldn't the child classes be used independently of the abstract class without causing issues? 子类不能独立于抽象类使用而不会引起问题吗?

Why use abstract classes 为什么要使用抽象类

Some may argue this being a good solution but abstract classes help to follow the DRY principle while interfaces don't help you with this. 有人可能会认为这是一个很好的解决方案,但是抽象类有助于遵循DRY原理,而接口则不能帮助您解决这一问题。 This comes at a cost however (eg changes in the base class implementation may break classes extending it) and you should generally prefer using interfaces if possible. 但是,这需要付出一定的代价(例如,对基类实现的更改可能会破坏扩展它的类),并且您通常应该尽可能使用接口。

Couldn't the child classes be used independently of the abstract class without causing issues? 子类不能独立于抽象类使用而不会引起问题吗?

Extending a particular predecessor lets you to be able to make different classes extending it be interchangeable. 扩展特定的前任产品使您能够使扩展它的不同类可以互换。

Let's say you need a bird of whatever kind. 假设您需要任何种类的鸟。 The fact both a duck and a hen extend a bird means you will accept both hens and ducks. 鸭子和母鸡都延伸鸟类这一事实意味着您将接受母鸡和鸭子。 You may say you only need flying birds and this will mean you won't accept hens (that jcan jump but not fly) any more but will keep accepting eagles. 您可能会说您只需要飞翔的鸟,这将意味着您将不再接受母鸡(jcan跳而不飞),但会继续接受老鹰。 But if you say you need a duck - this will mean you need a duck and won't accept birds of any other kinds. 但是,如果您说您需要一只鸭子-这意味着您需要一只鸭子,并且不接受任何其他种类的鸟类。 The fact a class extends another class (abstract or not) or an interface will let you pass it as an argument to a function that expects instances of the base class. 一个类扩展了另一个类(是否抽象)或接口的事实,使您可以将其作为参数传递给需要基类实例的函数。

You can use abstract classes when you need implement something in base class, and child classes should implement some another logic into same method. 当需要在基类中实现某些东西时,可以使用抽象类,而子类应在同一方法中实现另一种逻辑。 For example we need to implement services, which parse different type of file: 例如,我们需要实现服务,该服务可以解析不同类型的文件:

  • we have a base class, which set file name, method for store data into DB and abstract method - which parsing file 我们有一个基类,它设置文件名,用于将数据存储到数据库中的方法和用于解析文件的抽象方法
  • we have implementation for XLS, XLSX and CSV files, which has different implementation for method process. 我们有XLS,XLSX和CSV文件的实现,这些方法在方法处理方面有不同的实现。

It's a good solution. 这是一个很好的解决方案。 But it doesn't mean that you should use that way. 但这并不意味着您应该使用这种方式。 You can implement one of the pattern or do not use OOP at all. 您可以实现一种模式,或者根本不使用OOP。 It is just a one way how to implement a logic. 这只是实现逻辑的一种方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM