对象继承 原型继承
These days for your applications, a decoupled and encapsulated software system is ever more relevant. Reusability, maintenance, care, and sustainability play a major role in our software development projects — they are getting bigger and bigger. People, who try to master these challenges, read Robert C. Martins Clean Code, Clean Coder, or Clean Architecture. Actually, some of them follow his SOLID principles:
如今,对于您的应用程序而言,广告耦合和封装的软件系统变得越来越重要。 可重用性,维护,维护和可持续性在我们的软件开发项目中扮演着重要角色-它们变得越来越大。 试图应对这些挑战的人们请阅读Robert C. Martins的Clean Code , Clean Coder或Clean Architecture。 实际上,其中一些遵循他的SOLID原则:
Single Responsibility Principle
小号英格尔责任原则
Open-Closed-Principle
O闭式原理
Liskov-Substitution-Principle
大号 iskov-替代,原理
Interface-Segregation -Principle
我覆盖整个院落偏析-Principle
Dependency-Inversion-Principle
d ependency-反转原理
So, why should we care about the so called “Inheritance & Object Composition”? Because they are a big part of one of the aforementioned SOLID principles: the Open-Closed-Principle.
那么,为什么我们要关心所谓的“继承与对象组成”呢? 因为它们是上述SOLID原则之一的重要组成部分: Open-Closed-Principle 。
„Software entities … should be open for extension, but closed for modification.“
“软件实体……应为扩展而开放,但为修改而应闭合。”
What’s more, inheritance and object composition decide about whether your software application is going to be monolithic or decoupled. We need to understand these concepts to make our software systems cleaner.
而且,继承和对象组成决定了您的软件应用程序是整体的还是分离的。 我们需要了解这些概念,以使我们的软件系统更整洁。
In short, inheritance describes an “is a”-relationship between 2 participants. For example, the earth is a planet, which is a celestial body. Or a cube is a geometric figure.
简而言之,继承描述了两个参与者之间的“ 是 ”关系。 例如,地球是行星,是天体。 或立方体是一个几何图形。
Itchimonji Itchimonji制造Facts about inheritance:
关于继承的事实:
is one of few core concepts of object oriented programming
是面向对象编程的少数核心概念之一
a subclass inherits fields and methods from their base class/superclass 子类从其基类/超类继承字段和方法so, generally speaking, the subclass is a specialized model of its generalized base class
因此,一般而言, 子类是其广义基类的专门模型
properties or methods are only passed on according to their visibility (e.g. private, protected, public, …) and may be overwritten by their subclasses 属性或方法仅根据其可见性(例如,私有,受保护,公共等)传递,并可能被其子类覆盖 is supported by OOP — so handling is very simple 由OOP支持-因此处理非常简单definition at design time
设计时定义
implementations can be reused in the subclasses very easily 可以很容易地在子类中重用实现The “Gang of Four” (Design Patterns) describe inheritance as a white-box reuse, because the internals of base classes are visible to their subclasses. And because of the strong linkage between base and subclass, the modification of the base class can affect the subclass, too. So, the base class implementation breaks up the encapsulation of all subclasses — this might be hard to change later.
“四人帮”( 设计模式 )将继承描述为白盒重用 ,因为基类的内部对于其子类可见。 而且由于基类和子类之间的紧密联系,对基类的修改也会影响子类。 因此,基类的实现破坏了所有子类的封装-以后可能很难更改。
This relationship is tightly coupled and entails many code risks by changing the superclass. The more a class knows about another class, the more they are coupled. Only inheritance of abstract classes can prevent this.
这种关系紧密耦合,并且通过更改超类会带来许多代码风险。 一个班级对另一个班级的了解越多,他们之间的联系就越多。 只有抽象类的继承才能阻止这种情况 。
class Creature { private isNatural: boolean; protected size: number; public beAlive(): void { console.log('Im alive'); } constructor (isNatural: boolean) { this.isNatural = isNatural; }}class Human extends Creature { protected age: number; public setSize(value: number): void { this.size = value; } constructor(age: number) { super(true); this.age = age; this.beAlive(); }}class Worker extends Human { constructor(size: number) { super(38); this.beAlive(); this.setSize(size); }}An other technique of code reuse is object composition. In short, it describes a “has a”-relationship between 2 or more participants. For example, a car has got wheels, an engine, windows, doors, and a lot of electronic stuff.
代码重用的另一种技术是对象组合。 简而言之,它描述了两个或更多参与者之间的“ 具有 ”关系。 例如,汽车有车轮,引擎,窗户,门和许多电子设备。
Itchimonji Itchimonji制造Facts about object composition:
关于对象组成的事实:
is fundamental to every programming language (not only OOP)
对于每种编程语言 (不仅是OOP)都是至关重要的
it’s an assignment of a reference to other objects 这是对其他对象的引用的分配it can be accessed by interfaces (Dependency Inversion)
可以通过接口访问它( Dependency Inversion )
you can change this assignment whenever you want — so this runtime behaviour allows replacing different objects of the same type dynamically 您可以随时更改此分配-因此,此运行时行为允许动态替换相同类型的不同对象definition at runtime
运行时定义
The “Gang of Four” (Design Patterns) describe Object Composition as black-box reuse, because you can’t see the internal code — only the interface.
“四人帮”( 设计模式 )将对象组成描述为黑盒复用,因为您看不到内部代码—仅看到接口。
This loosely coupled concept and the interface-access allow more flexibility in code design, secure Uncle Bobs Open-Closed-Principle, and lead to encapsulation. Because your existing and working code will not be altered while you can still add new behaviour — you can change components and objects without any code risks and without having to think about code dependencies.
这种松散耦合的概念和接口访问使代码设计具有更大的灵活性 ,可确保Bobs叔叔的开闭原理,并导致封装。 因为在仍然可以添加新行为的同时不会更改现有和正在运行的代码,所以您可以更改组件和对象而没有任何代码风险,也不必考虑代码依赖性。
Besides, using object composition is a good method to mock test data.
此外,使用对象组合是模拟测试数据的好方法。
interface AbstractEngine { howMuchIsIt(): void;}class DieselEngine implements AbstractEngine { private cycle: string; private compressionRatio: string; public howMuchIsIt(): void { console.log('High initial and maintenance costs'); } constructor() { this.cycle = 'Diesel'; this.compressionRatio = 'high'; }}class PetrolEngine implements AbstractEngine { private cycle: string; private sounds: string; public howMuchIsIt(): void { console.log('Low initial and maintenance costs'); }constructor() { this.cycle = 'Otto'; this.sounds = 'Brumm brumm..'; }}class Car { public engine: AbstractEngine; public drive();}function buildCar(engine: AbstractEngine): Car { const result: Car = new Car(); result.engine = engine; return result;}function buildCarWithPetrolEngine(): Car { const result: Car = buildCar(new PetrolEngine()); result.howMuchIsIt(); // Low initial and maintenance costs return result;}function buildCarWithDieselEngine(): Car { const result: Car = buildCar(new DieselEngine()); result.howMuchIsIt(); // High initial and maintenance costs return result;}The “Gang of Four” write in Design Patterns, you should prefer composition over inheritance whenever you can, because of the decoupled principle.
“ 设计模式 ”中的“四人帮”一书,由于分离的原理,您应该在任何可能的情况下都希望使用组合而不是继承。
Both have got strengths and weaknesses, but most developers instinctively opt for inheritance. Maybe they learnt it through their education and gained more experience than with composition. Personally, I am using object composition more than inheritance.
两者都有优点和缺点 ,但是大多数开发人员本能地选择继承。 也许他们是通过教育学到的,比起作文,他们获得了更多的经验。 就个人而言,我使用的对象组合比继承更多。
What you prefer depends on your problem. Most UI frameworks are based on inheritance (e.g. WinForms in C#). On the other hand most Design Patterns use object composition.
您更喜欢哪种取决于您的问题。 大多数UI框架都是基于继承的(例如C#中的WinForms)。 另一方面,大多数设计模式都使用对象组合。
“Program to an interface, not an implementation.”
“编程到接口,而不是实现。”
The abstract factory pattern provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes.
抽象工厂模式提供了一种封装一组具有共同主题的单个工厂而无需指定其具体类的方法。
Usage:
用法:
to configure a system of many object families 配置许多对象族的系统 to provide a class library, which can be accessed by interfaces 提供一个类库,可以通过接口访问 to enclose creation and composition of objects 封装对象的创建和组成 to force the system to use a family of related objects 强制系统使用一系列相关对象Example for creating a theme feature:
创建主题功能的示例:
These days it’s very important to design our software applications more decoupled and encapsulated. Object composition is a concept to reuse code more flexibly. Inheritance is better known and easier to handle. Also, you can combine both concepts. I started to use object composition more often after reading the book “Design Patterns”. I learnt it is very important to build your software system in an easily maintainable way. We should try to be DRY and reuse our code.
如今,对我们的软件应用程序进行更解耦和封装的设计非常重要。 对象组合是一个可以更灵活地重用代码的概念。 继承是众所周知的且易于处理 。 另外,您可以将两个概念结合起来。 阅读“设计模式”一书后,我开始更频繁地使用对象组合。 我了解到以易于维护的方式构建软件系统非常重要。 我们应该尝试变干并重用我们的代码。
Design Patterns are great and it is fun to code them — object composition is a big part of it. Besides, you learn other coding techniques — for me, I now better understand Angular with its own art (Dependency inversion, observables, states, etc). It’s worth to take a look at them. Try it out!
设计模式很棒,对它们进行编码很有趣-对象组成是其中很大的一部分。 此外,您还将学习其他编码技术-对我而言,我现在对Angular有了自己的理解(依赖反转,可观察性,状态等)。 值得一看。 试试看!
Thank you and Happy Coding! :)
谢谢您,祝您编码愉快! :)
翻译自: https://medium.com/@itchimonji/inheritance-object-composition-84c9539eeaf9
对象继承 原型继承