Created
July 6, 2015 09:38
-
-
Save m00nlight/51171c9ba28b979fffd2 to your computer and use it in GitHub Desktop.
Ruby decorator pattern
This file contains 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
module Decorator | |
def initialize(decorated) | |
@decorated = decorated | |
end | |
def method_missing(method, *args) | |
args.empty? ? @decorated.send(method) : @decorated.send(method, args) | |
end | |
end | |
module Memoization | |
def memo(name) | |
@@lookup ||= Hash.new { |h, k| h[k] = {} } | |
f = instance_method(name) | |
define_method(name) do |args| | |
return @@lookup[name][args] if @@lookup[name].include?(args) | |
@@lookup[name][args] = f.bind(self).call(args) | |
end | |
end | |
end | |
module Memo | |
def memo(name) | |
@@cache = Hash.new | |
f = instance_method(name) | |
define_method(name) do |args| | |
return @@cache[args] if @@cache.include? args | |
@@cache[args] = f.bind(self).call(args) | |
end | |
end | |
end | |
class Calculator | |
extend Memoization | |
memo \ | |
def fact(n) | |
return 1 if n <= 1 | |
n * fact(n-1) | |
end | |
memo \ | |
def fib(n) | |
return 1 if n <= 1 | |
fib(n - 1) + fib(n - 2) | |
end | |
end | |
class C2 | |
extend Memo | |
memo \ | |
def fib(n) | |
return 1 if n <= 1 | |
fib(n - 1) + fib(n - 2) | |
end | |
memo \ | |
def fact(n) | |
return 1 if n <= 1 | |
n * fact(n - 1) | |
end | |
end | |
t1 = Calculator.new | |
p t1.fact(20) | |
p t1.fib(20) | |
p Calculator.new.fact(20) | |
p Calculator.new.fib(35) | |
t = C2.new | |
p t.fact(35) | |
p t.fib(35) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment