Skip to content

Instantly share code, notes, and snippets.

@jverzani
Created March 1, 2012 22:19
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jverzani/1953641 to your computer and use it in GitHub Desktop.
Save jverzani/1953641 to your computer and use it in GitHub Desktop.
example of singleton pattern
## Singleton pattern
Singleton <- setRefClass("Singleton",
fields=list(
Class="ANY",
instance="ANY"
),
methods=list(
initialize=function(...) {
"Override this by defining Class"
instance <<- NULL
callSuper(...)
},
get_instance=function(...) {
"Get a unique instance of the class defined in the subclasses initialize method"
if(is.null(instance))
instance <<- Class$new(...)
instance
}
))
SomeSingleObject <- setRefClass("SomeSingleObject",
contains="Singleton",
fields=c("property"), # fake, just to keep down warnings
methods=list(
initialize=function(...) {
Class <<- setRefClass("Class",
fields=list(
property="ANY"
),
methods=list(
initialize=function(...) {
initFields()
callSuper(...)
},
set_property=function(value) {
property <<- value
},
get_property=function() property
)
)
callSuper(...)
}
))$new()
a <- SomeSingleObject$get_instance()
b <- SomeSingleObject$get_instance() ## sam object
identical(a, b)
a$set_property("some value")
print(b$get_property())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment