Groovy 设计模式 -- 适配器模式

Adapter Pattern

http://groovy-lang.org/design-patterns.html#_adapter_pattern

适配器模式,对象存在一个接口, 此接口在此对象中不能被另外一类对象使用, 提供对象的适配接口,将此接口做包装,适配为另外一类接口。 这类模式也叫包装模式(wrapper pattern)

The Adapter Pattern (sometimes called the wrapper pattern) allows objects satisfying one interface to be used where another type of interface is expected. There are two typical flavours of the pattern: the delegation flavour and the inheritance flavour.

 

代表风格

class SquarePeg { def width } class RoundPeg { def radius } class RoundHole { def radius def pegFits(peg) { peg.radius <= radius } String toString() { "RoundHole with radius $radius" } }




class SquarePegAdapter { def peg def getRadius() { Math.sqrt(((peg.width / 2) ** 2) * 2) } String toString() { "SquarePegAdapter with peg width $peg.width (and notional radius $radius)" } }

 

将正方形适配为圆形接口。

 

继承模式

 

class SquarePeg { def width } class RoundPeg { def radius } class RoundHole { def radius def pegFits(peg) { peg.radius <= radius } String toString() { "RoundHole with radius $radius" } }


class SquarePegAdapter extends SquarePeg { def getRadius() { Math.sqrt(((width / 2) ** 2) * 2) } String toString() { "SquarePegAdapter with width $width (and notional radius $radius)" } }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值