抽象有什么用? [英] What is the use of Abstraction?
问题描述
我正在努力理解抽象在 Java 中的整体使用.
I'm struggling to understand the overall use of Abstraction in Java.
我一直在研究此链接中的一个示例:https://javatutorial.net/java-抽象例子我理解它的实现,但我不明白为什么它甚至是必要的.如果他们只是要在 2 个子类中再次创建,为什么他们的一个 calculateSalary 方法是在 Employee 类中创建的?
I have been working off an example in this link: https://javatutorial.net/java-abstraction-example I understand the implementation of it but I don't understand why its even necessary. Why is their a calculateSalary method made in the Employee class if they are just going to made again in the 2 subclasses?
推荐答案
抽象的整体使用是解耦的.要使用 Employee
,不需要知道实现,只需要知道接口和它的契约.例如,这用于 Collections.sort(List
:Collections.sort(...)
无需知道特定列表的实现即可对其进行排序.这提供了实现支持符合 List
界面.这个问题在这方面是相关的(#selfPromotion).更少的耦合导致更少的摩擦和整体更不脆弱的代码.
The overall use of abstraction is decoupling. To work with an Employee
, one does not need to know the implementation, only the interface and its contracts. This is, for example, used for Collections.sort(List<T> list)
: the programmers of Collections.sort(...)
did not need to know the implementation of a specific list in order to sort it. This provides the benefit that the implementation support future code that conforms to the List
interface. This question is related in that respect (#selfPromotion). Less coupling leads to less friction and overall less fragile code.
也就是说,您提供的示例很糟糕,因为它违反了单一职责原则:计算薪水不是Employee
实例的责任.为此,我们应该有一个单独的对象来计算工资,基于 Employee
实例和一些工作时间.在内部,这个 Uber 计算器可以使用一个责任链,其中包含一个Calculator
per Employee
- 实施,将 Employee
与他们的工资计算方式分离.这提供了可扩展性和灵活性的额外好处:如果计算薪水的方式发生变化(例如,公司可能会更改政策,以便每个 FullTimeEmployee
获得相同的薪水,或者公司可能想要计算薪水按周而不是按月),使用 FullTimeEmployee
的其他服务表示不受影响).
That said, the example you provided is a poor one since it violates the Single Responsibility Principle: It is not the responsibility of an Employee
instance to calculate the salary. For this, we should have a separate object that calculates the salary, based on an Employee
-instance and some hours worked. Internally, this Uber-calculator could use a Chain of Responsibility, which hold one Calculator
per Employee
-Implementation, decoupling the Employee
from how their salary is calculated. This provides the added benefit of extensibility and flexibility: if the way a salary is calculated changes (e.g. maybe the company switches policy so that each FullTimeEmployee
earns the same salary, or maybe the company wants to calculate the salary on a by-week instead of a by-month basis), other services using the FullTimeEmployee
say unaffected).
这篇关于抽象有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!