Menu
Coddy logo textTech

Strategy Pattern

Part of the Object Oriented Programming section of Coddy's R journey. Lesson 45 of 57.

The strategy pattern makes an algorithm replaceable: the code that needs it receives it as an argument. In R a function is a value, so the strategy is a function passed in, and the caller picks which one:

no_discount <- function(total) total
half_price <- function(total) total / 2
checkout <- function(total, discount = no_discount) {
  paste("pay", discount(total))
}
print(checkout(80))
print(checkout(80, half_price))

Output:

[1] "pay 80"
[1] "pay 40"

A named list of strategies lets the program choose one by name at run time, for example from user input:

pricing <- list(
  regular = function(p) p,
  member = function(p) p * 0.9,
  staff = function(p) p * 0.7
)
for (who in c("regular", "member", "staff")) cat(who, pricing[[who]](50), "\n")

Output:

regular 50 
member 45 
staff 35 

Strategies with settings are built by factories. percent_off(10) returns a new strategy function that remembers its percentage:

percent_off <- function(pct) function(total) total * (1 - pct / 100)
fixed_off <- function(amount) function(total) max(0, total - amount)
rules <- list(percent_off(10), percent_off(25), fixed_off(30))
print(vapply(rules, function(r) r(100), numeric(1)))

Output:

[1] 90 75 70

An object can hold its strategy in a field and swap it later. The rest of the object stays the same:

new_sorter <- function(key) structure(list(key = key), class = "sorter")
sort_with <- function(s, words) words[order(s$key(words))]
by_length <- function(w) nchar(w)
by_last_letter <- function(w) substring(w, nchar(w))
s <- new_sorter(by_length)
words <- c("pear", "fig", "banana")
print(sort_with(s, words))
s$key <- by_last_letter
print(sort_with(s, words))

Output:

[1] "fig"    "pear"   "banana"
[1] "banana" "fig"    "pear"  
challenge icon

Challenge

Easy

Shipping is chosen by a strategy: a function of the cart's total weight and its subtotal that returns the shipping cost. In Strategies.R write:

  • standard(kg, subtotal): 4.99 plus 1 per kg;
  • express(kg, subtotal): twice the standard cost;
  • free_over(limit): returns a strategy that costs 0 when the subtotal is at least limit and the standard cost otherwise.

In Cart.R, new_cart(strategy) and add_item() are given; complete subtotal(cart) and shipping_cost(cart), which calls the cart's strategy. The supplied code reads the strategy (standard, express or free_over 50), then items book 12 0.5 (name, price, kg), and prints the totals.

Your code goes in Strategies.R and Cart.R. main.R holds the supplied input/output code and cannot be edited.

Try it yourself

source("Strategies.R")
source("Cart.R")

# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
p <- strsplit(input[1], " ")[[1]]
rule <- if (p[1] == "free_over") free_over(as.numeric(p[2])) else get(p[1])
cart <- new_cart(rule)
for (line in input[-1]) {
  q <- strsplit(line, " ")[[1]]
  cart <- add_item(cart, q[1], as.numeric(q[2]), as.numeric(q[3]))
}
cat(sprintf("items: %.2f, shipping: %.2f, total: %.2f", subtotal(cart), shipping_cost(cart), subtotal(cart) + shipping_cost(cart)), "\n", sep = "")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming

Practice on your own: Online R compiler