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)" } }