首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >适配器模式与Liskov替换

适配器模式与Liskov替换
EN

Stack Overflow用户
提问于 2011-02-25 15:00:47
回答 1查看 2.7K关注 0票数 9

Adapter设计模式用于将类(Target)的接口转换为客户期望的另一个接口(适配器)。适配器允许不兼容的类一起工作,否则由于它们的接口不兼容而无法工作。

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

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

下面是绘图编辑器的一个示例:

代码语言:javascript
复制
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接口适应形状的接口:

  1. 通过继承形状的接口和TextView的实现(适配器模式的类版本)
  2. 通过在TextView对象中组合一个TextShape实例并使用TextView实例( Adapter的对象版本)实现TextShape的接口。

类适配器

代码语言:javascript
复制
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代换原理

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-02-25 23:15:16

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

这可能违反了单一责任原则,但我不确定这是适配器实现中的一个巨大问题。

我一般更喜欢委托代表的方式。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5118726

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档