Learn R Programming

R6P (version 0.4.0)

Singleton: Singleton

Description

Enforces a single instance of a class and provides a global access point.

Arguments

Methods

Public methods


Method new()

Create or retrieve an object

Usage

Singleton$new()

Details

This is an abstract base class. Instantiating Singleton directly triggers an error. Classes inheriting from Singleton share a single instance.

See Also

Other base design patterns: NullObject(), ValueObject()

Examples

Run this code
# See more examples at 
address <- function(x) sub("", "\\1", capture.output(x))

# In this example we implement a `Counter` that inherits the qualities of Singleton
Counter <- R6::R6Class("Counter", inherit = R6P::Singleton, public = list(
  count = 0,
  add_1 = function() {
    self$count <- self$count + 1
    invisible(self)
  }
))

# Whenever we call the constructor on `Counter`, we always get the exact same instance:
counter_A <- Counter$new()
counter_B <- Counter$new()

identical(counter_A, counter_B, ignore.environment = FALSE)

# The two objects are equal and located at the same address; thus, they are the same object.

# When we make a change in any of the class instances, the rest are changed as well.

# How many times has the counter been increased?
counter_A$count

# Increase the counter by 1
counter_A$add_1()

# How many times have the counters been increased?
counter_A$count
counter_B$count

Run the code above in your browser using DataLab