zoukankan      html  css  js  c++  java
  • 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)"
        }
    }
  • 相关阅读:
    hdu 1163 Eddy's digital Roots (数学)
    hdu 2546 饭卡 (01背包)
    hdu 1059 Dividing(多重DP)
    晚霞
    最佳学习方法
    [备忘]求两数最大公约,最小公倍数
    不眠的夏夜
    超女唱《八荣八耻》:好完美的恶搞啊
    公司展会上的德国MM
    我玩游戏
  • 原文地址:https://www.cnblogs.com/lightsong/p/8724306.html
Copyright © 2011-2022 走看看