سؤال

When talking about the C++ implementation the Adapter pattern in book "DesignPatterns: Elements of Reusable Object-Oriented Software", it goes like this:

[...] In a C++ implementation of a class adapter, Adapter would inherit publicly from Target and privately from Adaptee. [...]

enter image description here

Can someone explain the reason here?

هل كانت مفيدة؟

المحلول

In object-oriented programming, relationships between classes of objects can be classified as "is-a", "has-a" or "is-implemented-in-terms-of".

When it comes to C++, "is-a" relationship can (and should) be implemented through public inheritance.

"Has-a" can (and should) be implemented through containment. It makes the using class depend upon only the public parts of the used class. In rare cases as a last resort you might want to implement "has-a" through non-public inheritance, but usually it's an indicator of bad design.

"Is-implemented-in-terms-of" can be implemented through either containment or non-public inheritance.

Non-public inheritance allows you to access the protected parts of the used class, override its virtual methods, etc. It also helps others to understand your intentions better (as long as non-public inheritance expresses "is-implemented-in-terms-of" and containment expresses "has-a").

On the other hand, containment has some advantages of its own. For example, it allows having multiple instances of the used class. It also allows us to implement Dependency Injection and thus satisfy the Dependency Inversion Principle.

Adapter "is-a" subtype of Target and at the same time "is-implemented-in-terms-of" Adaptee. Therefore Adapter should inherit publicly from Target. But you can use either private inheritance or containment to implement the "is-implemented-in-terms-of" relationship between Adapter and Adaptee.

One of the main criteria used to decide which type of relationship to use, is the type of adapter pattern you want to implement (class adapter or object adapter).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top