Skip to content

Commit 8e442cf

Browse files
committed
Prefer composition over inheritance
1 parent b4e287c commit 8e442cf

File tree

1 file changed

+14
-1
lines changed

1 file changed

+14
-1
lines changed

README-zh-CN.md

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1741,24 +1741,37 @@ const car = new Car()
17411741
```
17421742
**[⬆ 返回顶部](#代码整洁的-javascript)**
17431743

1744-
### Prefer composition over inheritance
1744+
### 组合优先于继承
17451745
As stated famously in [*Design Patterns*](https://en.wikipedia.org/wiki/Design_Patterns) by the Gang of Four,
17461746
you should prefer composition over inheritance where you can. There are lots of
17471747
good reasons to use inheritance and lots of good reasons to use composition.
17481748
The main point for this maxim is that if your mind instinctively goes for
17491749
inheritance, try to think if composition could model your problem better. In some
17501750
cases it can.
17511751

1752+
正如[*设计模式四人帮*](https://en.wikipedia.org/wiki/Design_Patterns)所述, 如果可能,
1753+
你应该优先使用组合而不是继承。 有许多好的理由去使用继承, 也有许多好的理由去使用组合。这个格言
1754+
的重点是, 如果你本能的观点是继承, 那么请想一下组合能否更好的为你的问题建模。 很多情况下它真的
1755+
可以。
1756+
17521757
You might be wondering then, "when should I use inheritance?" It
17531758
depends on your problem at hand, but this is a decent list of when inheritance
17541759
makes more sense than composition:
17551760

1761+
那么你也许会这样想, “我什么时候改使用继承?” 这取决于你手上的问题, 不过这儿有一个像样的列表说
1762+
明什么时候继承比组合更好用:
1763+
17561764
1. Your inheritance represents an "is-a" relationship and not a "has-a"
17571765
relationship (Human->Animal vs. User->UserDetails).
17581766
2. You can reuse code from the base classes (Humans can move like all animals).
17591767
3. You want to make global changes to derived classes by changing a base class.
17601768
(Change the caloric expenditure of all animals when they move).
17611769

1770+
1771+
1. 你的继承表示"是一个"的关系而不是"有一个"的关系(人类->动物 vs 用户->用户详情);
1772+
2. 你可以重用来自基类的代码(人可以像所有动物一样行动);
1773+
3. 你想通过基类对子类进行全局的修改(改变所有动物行动时的热量消耗);
1774+
17621775
**Bad:**
17631776
```javascript
17641777
class Employee {

0 commit comments

Comments
 (0)