tidylab / R6P

Leverage the power of R design patterns to solve real-world problems in software architecture and design
https://tidylab.github.io/R6P/
Other
6 stars 0 forks source link

Decorator Design Pattern #15

Open harell opened 3 years ago

harell commented 3 years ago

Intent

Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

Also Known As

Wrapper

Example

print_command_and_execute <- function(command) {
    function_name <- as.character(substitute(command))
    function_name <- function_name[length(function_name)]
    wrapper <- function(...){
        args <- list(...)
        args_as_string <- character(0)
        for(i in seq_len(length(args))) 
            args_as_string[i] <- paste(names(args)[i],"=",as.character(args[i]))
        args_as_string <- paste(args_as_string, collapse = ", ")

        message("\033[43m\033[44m", function_name, "(", args_as_string, ")", "\033[43m\033[49m")
        return(command(...))
    }

    return(wrapper)
}

setdiff <- print_command_and_execute(base::setdiff)

> setdiff(x = 1:3, y = 1)
setdiff(x = 1:3, y = 1)
[1] 2 3
harell commented 3 years ago

Real-world examples

harell commented 3 years ago

Further reading