Return to Snippet

Revision: 5019
at February 5, 2008 17:40 by narkisr


Initial Code
// the decorated class
package design.patterns.decorator

class Logger {
    def log(text) {
        println(text)
    }
}

// the naive implementation
package design.patterns.decorator

class LowerCaseLogger extends Logger {

    def logger

    LowerCaseLogger(log) {
        logger = log
    }

    def log(text) {
        logger.log(text.toLowerCase())
    }


    public static void main(String[] args) {
        def logger = new LowerCaseLogger(new Logger())
        logger.log('HELLO DECORATION')
    }
}

// the more general implementation
package design.patterns.decorator

class GenericLowerLogger {
    private delegate

    GenericLowerLogger(delegate) {
        this.delegate = delegate
    }
    def invokeMethod(String name, args) {
        def newargs = args.collect {arg ->
            if (arg instanceof String) return arg.toLowerCase()
            else return arg
        }
        delegate.invokeMethod(name, newargs)
    }

    public static void main(String[] args) {
        def logger = new GenericLowerLogger(new Logger())
        logger.log('HELLO DECORATION')// hello decoration
    }
}

Initial URL

                                

Initial Description
Decorator design pattern implemented in Groovy, two implementation are provided, the first is naive and not general, the second is MOP based and can be used in much more scenarios.

Initial Title
Decorator Design Pattern Groovy

Initial Tags
design, groovy

Initial Language
Groovy