在 “DesignPatterns: Elements of Reusable Object-Oriented Software” 一书中谈到 C++ 实现 Adapter
模式时,它是这样的这个:
[...] In a C++ implementation of a class adapter,
Adapter
would inherit publicly fromTarget
and privately fromAdaptee
. [...]
有人能解释一下这里的原因吗?
最佳答案
在面向对象编程中,对象类之间的关系可以分为“is-a”、“has-a”或“is-implemented-in-terms-of”。
对于 C++,“is-a”关系可以(并且应该)通过公共(public)继承来实现。
“有一个”可以(而且应该)通过遏制来实现。它使 using 类仅依赖于 used 类的公共(public)部分。在极少数情况下,作为最后的手段,您可能希望通过非公共(public)继承实现“has-a”,但这通常表明设计不当。
“Is-implemented-in-terms-of”可以通过包含或非公共(public)继承来实现。
非公有继承可以让你访问所用类的 protected 部分,覆盖它的虚方法等,也可以帮助别人更好地理解你的意图(只要非公有继承表示“is-implemented-in -terms-of”和包含表示“has-a”)。
另一方面,遏制也有其自身的一些优势。例如,它允许使用类的多个实例。它还允许我们实现依赖注入(inject),从而满足依赖倒置原则。
适配器 “是一个” Target 的子类型,同时“is-implemented-in-terms-of”适配器。 因此 Adapter 应该公开继承自 Target。 但是您可以使用私有(private)继承或包含来实现 Adapter 和 Adaptee 之间的“is-implemented-in-terms-of”关系。
用于决定使用哪种类型的关系的主要标准之一是您要实现的适配器模式类型(类适配器或对象适配器)。
关于c++ - 为什么 Adapter 会公开继承 Target 而私有(private)继承 Adapter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22860536/