结构型 --- 适配器模式

举报
斌哥来了 发表于 2021/07/29 10:30:25 2021/07/29
6.3k+ 0 0
【摘要】 // 假设你有两个接口相互兼容的类:圆孔( Round Hole )和圆钉( Round Peg )。 class RoundHole is constructor RoundHole ( radius ) { ... } method getRadius () is // 返回孔的半径。 met...








// 假设你有两个接口相互兼容的类:圆孔( Round Hole )和圆钉( Round Peg )。

class RoundHole is

constructor RoundHole ( radius ) { ... }

method getRadius () is

// 返回孔的半径。

method fits ( peg : RoundPeg ) is

return this . getRadius () >= peg . radius ()

class RoundPeg is

constructor RoundPeg ( radius ) { ... }

method getRadius () is

// 返回钉子的半径。

// 但还有一个不兼容的类:方钉( Square Peg )。

class SquarePeg is

constructor SquarePeg ( width ) { ... }

method getWidth () is

// 返回方钉的宽度。

// 适配器类让你能够将方钉放入圆孔中。它会对 RoundPeg 类进行扩展,以接收适

// 配器对象作为圆钉。

class SquarePegAdapter extends RoundPeg is

// 在实际情况中,适配器中会包含一个 SquarePeg 类的实例。

private field peg : SquarePeg

constructor SquarePegAdapter ( peg : SquarePeg ) is

this . peg = peg

method getRadius () is

// 适配器会假扮为一个圆钉,

// 其半径刚好能与适配器实际封装的方钉搭配起来。

return peg . getWidth () * Math . sqrt ( 2 ) / 2

// 客户端代码中的某个位置。

hole = new RoundHole ( 5 )

rpeg = new RoundPeg ( 5 )

hole . fits ( rpeg ) // true

small_sqpeg = new SquarePeg ( 5 )

large_sqpeg = new SquarePeg ( 10 )

hole . fits ( small_sqpeg ) // 此处无法编译(类型不一致)。

small_sqpeg_adapter = new SquarePegAdapter ( small_sqpeg )

large_sqpeg_adapter = new SquarePegAdapter ( large_sqpeg )

hole . fits ( small_sqpeg_adapter ) // true

hole . fits ( large_sqpeg_adapter ) // false





【版权声明】本文为华为云社区用户原创内容,未经允许不得转载,如需转载请自行联系原作者进行授权。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

作者其他文章

评论(0

抱歉,系统识别当前为高风险访问,暂不支持该操作

    全部回复

    上滑加载中

    设置昵称

    在此一键设置昵称,即可参与社区互动!

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。