-
-
Save gwd999/7f1209267998cdcb55ac to your computer and use it in GitHub Desktop.
example of singleton pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## 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