Menu
Coddy logo textTech

Factory Pattern

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

A factory is a function that creates objects so that the caller does not need to know the class or its constructor. It takes a description, such as a type name, and returns the right object:

area <- function(s) UseMethod("area")
area.circle <- function(s) pi * s$r^2
area.square <- function(s) s$side^2
make_shape <- function(type, size) {
  switch(type,
    circle = structure(list(r = size), class = "circle"),
    square = structure(list(side = size), class = "square"))
}
for (t in c("circle", "square")) cat(t, round(area(make_shape(t, 2)), 2), "\n")

Output:

circle 12.57 
square 4 

For a type it does not know, switch() returns NULL. A factory should stop with a message that names the type instead, so the mistake shows up where it was made:

make_shape <- function(type, size) {
  switch(type,
    circle = structure(list(r = size), class = "circle"),
    square = structure(list(side = size), class = "square"),
    stop("unknown shape: ", type, call. = FALSE))
}
msg <- tryCatch(make_shape("hexagon", 1), error = function(e) conditionMessage(e))
cat(msg)

Output:

unknown shape: hexagon

A registry keeps the constructors in a named list, so the factory itself never changes. Here the registry is an environment, and register_shape() adds a new kind while the program runs:

registry <- new.env()
register_shape <- function(name, maker) assign(name, maker, envir = registry)
make_shape <- function(name, ...) {
  if (!exists(name, envir = registry, inherits = FALSE)) stop("unknown shape: ", name, call. = FALSE)
  get(name, envir = registry)(...)
}
register_shape("circle", function(r) structure(list(r = r), class = "circle"))
register_shape("rect", function(w, h) structure(list(w = w, h = h), class = "rect"))
print(class(make_shape("rect", 2, 3)))
print(sort(ls(registry)))

Output:

[1] "rect"
[1] "circle" "rect"  

Code that uses the objects depends only on the generics, such as area(). A new class that is registered and has an area() method works with that code without any change to it:

registry <- new.env()
register_shape <- function(name, maker) assign(name, maker, envir = registry)
make_shape <- function(name, ...) get(name, envir = registry)(...)
area <- function(s) UseMethod("area")
total_area <- function(shapes) sum(vapply(shapes, area, numeric(1)))
register_shape("square", function(a) structure(list(a = a), class = "square"))
area.square <- function(s) s$a^2
register_shape("tri", function(b, h) structure(list(b = b, h = h), class = "tri"))
area.tri <- function(s) s$b * s$h / 2
print(total_area(list(make_shape("square", 2), make_shape("tri", 4, 3))))

Output:

[1] 10
challenge icon

Challenge

Easy

A record can be exported in several formats. Exporters.R holds the generic export(exporter, record) and the method for csv_exporter, which returns the values joined by commas. Complete the two other methods there:

  • json_exporter: {"name": "Ada", "age": "36"};
  • text_exporter: name=Ada; age=36.

Then write the factory make_exporter(format) in Factory.R: csv, json or text give an empty list with the class csv_exporter, json_exporter or text_exporter, and any other format stops with unknown format: xml (use call. = FALSE). The supplied code reads the field names and the values, then format names, and prints each export or error: and the message.

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

Try it yourself

source("Exporters.R")
source("Factory.R")

# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
fields <- strsplit(input[1], ",")[[1]]
values <- strsplit(input[2], ",")[[1]]
record <- setNames(values, fields)
for (fmt in input[-(1:2)]) {
  out <- tryCatch(export(make_exporter(fmt), record), error = function(e) paste("error:", conditionMessage(e)))
  cat(out, "\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