Decorator Pattern
Part of the Object Oriented Programming section of Coddy's R journey. Lesson 46 of 57.
A decorator wraps something and adds behaviour while keeping the same interface. For a function, the decorator takes a function and returns a new function that does extra work around the call:
with_logging <- function(f, name) {
function(x) {
cat("calling", name, "with", x, "\n")
f(x)
}
}
double <- function(x) x * 2
logged <- with_logging(double, "double")
print(logged(21))Output:
calling double with 21
[1] 42A decorator can remember results. with_cache() keeps every answer in an environment and calls the wrapped function only for new arguments:
with_cache <- function(f) {
cache <- new.env()
function(x) {
key <- as.character(x)
if (!exists(key, envir = cache, inherits = FALSE)) assign(key, f(x), envir = cache)
get(key, envir = cache)
}
}
work <- 0
slow_square <- function(x) {
work <<- work + 1
x^2
}
fast <- with_cache(slow_square)
for (x in c(3, 4, 3, 3, 4)) fast(x)
cat("results computed:", work)Output:
results computed: 2Objects can be decorated too. Each decorator is an object that holds the object it wraps in a field and answers the same generics, adding its part and asking the inner object for the rest:
cost <- function(d) UseMethod("cost")
describe <- function(d) UseMethod("describe")
cost.coffee <- function(d) 2
describe.coffee <- function(d) "coffee"
with_milk <- function(inner) structure(list(inner = inner), class = "milk")
cost.milk <- function(d) cost(d$inner) + 0.5
describe.milk <- function(d) paste(describe(d$inner), "+ milk")
cup <- with_milk(with_milk(structure(list(), class = "coffee")))
cat(describe(cup), "=", cost(cup))Output:
coffee + milk + milk = 3Decorators stack, and their order matters: the outermost one runs first on the way in and last on the way out:
exclaim <- function(f) function(s) paste0(f(s), "!")
twice <- function(f) function(s) paste(f(s), f(s))
greet <- function(name) paste("hi", name)
a <- twice(exclaim(greet))
b <- exclaim(twice(greet))
cat(a("ada"), "/", b("ada"))Output:
hi ada! hi ada! / hi ada hi ada!Challenge
EasyDrinks are decorated with extras. Drink.R holds the generics cost() and describe() and the base drink, new_coffee(), which costs 2 and describes itself as coffee. In Extras.R write three decorators, each an object that holds the drink it wraps in the field inner:
add_milk(d): classmilk, adds 0.50 and+ milk;add_sugar(d): classsugar, adds 0.20 and+ sugar;add_syrup(d, flavour): classsyrupwith the fieldflavour, adds 0.80 and+ vanilla syrup.
Write their cost() and describe() methods by asking the inner drink first. The supplied code reads lines such as milk,syrup vanilla,sugar (an empty line is a plain coffee) and prints coffee + milk + vanilla syrup + sugar: 3.50.
Your code goes in Drink.R and Extras.R. main.R holds the supplied input/output code and cannot be edited.
Try it yourself
source("Drink.R")
source("Extras.R")
# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
for (line in input) {
d <- new_coffee()
if (nchar(line) > 0) for (extra in strsplit(line, ",")[[1]]) {
p <- strsplit(extra, " ")[[1]]
d <- switch(p[1], milk = add_milk(d), sugar = add_sugar(d), syrup = add_syrup(d, p[2]))
}
cat(sprintf("%s: %.2f", describe(d), cost(d)), "\n", sep = "")
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1S3 Basics
Working With FilesLists With a ClassConstructor FunctionsPrint and Format MethodsValidators and HelpersRecap - Temperatures4Encapsulation in R
Closures as ObjectsEnvironments as ObjectsAccessor FunctionsGuarding StateRecap - Parking Meter2S3 Generics and Methods
Generics and UseMethodDefault MethodsMethods for Base GenericsNextMethod BasicsRecap - Shape Areas8Reference Classes
Defining Reference ClassesMethods and Field UpdatesCopy SemanticsInheritance and callSuperRecap - Task Queue11Project: Library Management
Books and MembersBorrowing BooksPractice on your own: Online R compiler