gpt4 book ai didi

design-patterns - 适配器模式与 Liskov 替换

转载 作者:行者123 更新时间:2023-12-04 04:23:06 25 4
gpt4 key购买 nike

适配器设计模式用于将一个类的接口(interface)(目标)转换为客户期望的另一个接口(interface)(适配器)。适配器让不兼容的类可以一起工作,因为它们的接口(interface)不兼容。

适配器模式可以通过两种方式实现,继承 (适配器模式的类版本)和组合(适配器模式的对象版本)。

我的问题是关于使用继承实现的适配器模式的类版本。

这是绘图编辑器的示例:

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() { }
}

我们想重用TextView类来实现TextShape,但是接口(interface)不同,所以TextView和Shape对象不能互换使用。

是否应该更改 TextView 类以符合形状界面?也许不是。

TextShape 可以通过以下两种方式之一使 TextView 界面适应形状的界面:
  • 通过继承Shape的接口(interface)和TextView的实现(Adapter模式的类版)
  • 通过在 TextShape 对象内部组成一个 TextView 实例,并使用 TextView 实例(适配器模式的对象版本)实现 TextShape 的接口(interface)。

  • 类适配器

    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
    }

    现在的问题:-)。
    TextShape 是否继承自 Shape 尤其是 TextView 是有效的"is"关系?如果没有,是否违反 Liskov's Substitution Principle ?

    最佳答案

    它不违反 Liskov 替换原则,除非您在子类中有某些东西使其行为方式对父类(super class)没有意义(违反父类(super class)的契约(Contract))。这当然是不完整的代码,但我没有看到任何迹象。

    它可能违反 Single Responsibility Principle ,但我不确定这是适配器实现中的一个大问题。

    我通常更喜欢委托(delegate)方式。

    关于design-patterns - 适配器模式与 Liskov 替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5118726/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com