# NOT RUN {
library(R6)
## Create two decorators
# Works with active bindings...
dec1 <- DecoratorClass("dec1", active = list(hi = function() "Hi World"))
# And public fields...
dec2 <- DecoratorClass("dec2", public = list(goodbye = "Goodbye World"))
## Create an object to decorate
oop <- ooplah$new()
oop$hello()
## Decorate with dec1 by constructing dec1 with object oop:
dec_oop <- dec1$new(oop) # equiv `decorate(oop, dec1)`
## We have all original methods from oop
dec_oop$hello()
# It's inherited methods
dec_oop$init
# And now decorated methods
dec_oop$hi
## We can decorate again
redec_oop <- dec2$new(dec_oop)
redec_oop$hello()
redec_oop$init
redec_oop$hi
# And now
redec_oop$goodbye
# Notice the class reflects all decorators, the original object and parents,
# and adds the 'Decorator' class
class(redec_oop)
## Decorators also work with inheritance
parent_dec <- DecoratorClass("parent_dec",
public = list(hi = function() "Hi!"))
child_dec <- DecoratorClass("child_dec", inherit = parent_dec)
dec_oop <- child_dec$new(ooplah$new())
dec_oop$hi()
## Three possibilities if the method/field name already exists:
oop <- ooplah$new()
exists_dec <- DecoratorClass("exists_dec",
public = list(hello = function() "Hi!"))
# 1. skip (default)
oop$hello()
exists_dec$new(oop, exists = "skip")$hello()
# 2. error
# }
# NOT RUN {
exists_dec$new(oop)
exists_dec$new(oop, exists = "error")
# }
# NOT RUN {
# 3. overwrite
oop$hello()
exists_dec$new(oop, exists = "overwrite")$hello()
## Cloning
# Note that by default the decorated object is not cloned
dec <- DecoratorClass("dec", active = list(hi = function() "Hi World"))
dec_oop <- dec$new(oop)
dec_oop$logically
oop$logically <- FALSE
dec_oop$logically
# }
Run the code above in your browser using DataLab