Adapter设计模式用于将类(Target)的接口转换为客户期望的另一个接口(适配器)。适配器允许不兼容的类一起工作,否则由于它们的接口不兼容而无法工作。
适配器模式可以通过两种方式实现,一种是继承( Adapter模式的类版本),另一种是组合( Adapter模式的对象版本)。
我的问题是关于使用继承实现的适配器模式的类版本。
下面是绘图编辑器的一个示例:

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() { }
}我们希望重用TextView类来实现TextShape,但是接口是不同的,因此TextView和Shape对象不能互换使用。
应该更改TextView类以符合形状接口吗?也许不是。
TextShape可以通过以下两种方式之一使TextView接口适应形状的接口:
类适配器

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
} 以下是问题:)。TextShape从形状继承,特别是从TextView继承是有效的“是”关系吗?如果没有,这是否违反了Liskov代换原理
发布于 2011-02-25 23:15:16
它不会违反Liskov替换原则,除非子类中有某种东西使它的行为方式对超类(违反超类的契约)没有意义。当然,这是不完整的代码,但我没有看到任何迹象。
这可能违反了单一责任原则,但我不确定这是适配器实现中的一个巨大问题。
我一般更喜欢委托代表的方式。
https://stackoverflow.com/questions/5118726
复制相似问题