Adapter template implementation

The adapter design pattern is used to convert the class interface (Target) to another interface (Adaptee). The adapter allows incompatible classes to work together, which otherwise could not be associated with their incompatible interfaces.

An adapter template can be implemented in two ways: Inheritance (adapter template version class) and composition (object version of an adapter template).

My question is about the version of the adapter class that is implemented using Inheritance.

Here is an example of a drawing editor:

Figure 1:

interface Shape { Rectangle BoundingBox(); Manipulator CreateManipulator(); } class TextView { public TextView() { } public Point GetOrigin() { } public int GetWidth() { } public int GetHeight() { } } interface Shape { Rectangle BoundingBox(); Manipulator CreateManipulator(); } class TextView { public TextView() { } public Point GetOrigin() { } public int GetWidth() { } public int GetHeight() { } } 

We would like to reuse the TextView class to implement TextShape, but the interfaces are different, so TextView and Shape objects cannot be used interchangeably.

Should the TextView class be changed to match the form interface? Probably no.

TextShape can adapt the TextView interface to the form interface in one of two ways:

  • Inheriting the Shape interface and TextView implementation (adapter adapter class version)
  • By creating an instance of TextView inside a TextShape object and implementing the TextShape interface using an instance of TextView (object version of the adapter template).

Class adapter

Figure 2:

 interface Shape { Rectangle BoundingBox(); Manipulator CreateManipulator(); } class TextView { public TextView() { } public Point GetOrigin() { } public int GetWidth() { } public int GetHeight() { } } class TextShape : TextView, Shape { public Rectangle BoundingBox() { Rectangle rectangle; int x, y; Point p = GetOrigin(); x = GetWidth(); y = GetHeight(); //... return rectangle; } #region Shape Members public Rectangle Shape.BoundingBox() { return new TextBoundingBox(); } public Manipulator Shape.CreateManipulator() { return new TextManipulator(); } #endregion } 

Now to the question :-). Is TextShape an inheritance from Shape and, in particular, from TextView a valid "is" relationship? And if not, does he violate the Liskov Principle of Replacement ?

+8
design-patterns adapter
source share
1 answer

This does not violate the Liskov Substitution Principle if you have something in the subclass that forces it to behave in a way that makes no sense to the superclass (violating the superclass contract). Of course, this is incomplete code, but I see no signs of this.

This may violate the principle of single responsibility , but I'm not sure that this is a huge problem in the implementation of the adapter.

I usually prefer to delegate.

+4
source share

All Articles