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)"
        }
    }
  • 相关阅读:
    MySQL基础
    mysql新
    第四章 常用模块
    第三章 函数编程
    第二章 数据类型和文件操作
    基础语法
    day24 面向对象与实例属性
    day21
    详解 Eclipse 中的快速 Java 编码(代码模板)
    补缴2个月社保折腾1年多 刁钻政策玩死人
  • 原文地址:https://www.cnblogs.com/lightsong/p/8724306.html
Copyright © 2011-2022 走看看