Multiple classes question

Hi.

I need to create a class “Getter” that exposes a method “retrieve”
implemented differently depending on what backend is chosen.

The public API could be something like:
getter = Getter.new(:backend => “DB”)
getter.retrieve (where retrieve is implemented in a separate module or
class called DB)

What’s the best way to design such a class/module structure?

-M.

This is known as the strategy pattern:

Googling around for ‘ruby strategy pattern’ turns up some interesting
things, like this: http://tangleofwire.net/the-strategy-pattern-in-ruby

How about a factory pattern? Something like this:

class Getter
def initialize(factory)
@factory = factory
end

def create(hash)
@factory.create(hash)
end
end

class GetterFactory
def create(hash)
case hash[:backend]
when ‘DB’ then DB.new
when ‘MyFile’ then MyFile.new
else raise “Backend type not recognized”
end
end
end

class DB
def retrieve
puts “DB#retrieve”
end
end

class MyFile
def retrieve
puts “MyFile#retrieve”
end
end

getter = Getter.new(GetterFactory.new)
g = getter.create(:backend => ‘DB’)
g.retrieve

–output:–
DB#retrieve

Or, if you prefer this interface:

Getter.factory = GetterFactory.new
getter = Getter.create(:backend => ‘DB’)
getter.retrieve

then you can do this:

class Getter
@factory = ‘’

class <<self
attr_accessor :factory
end

def self.create(hash)
@factory.create(hash)
end
end

class GetterFactory
def create(hash)
case hash[:backend]
when ‘DB’ then DB.new
when ‘MyFile’ then MyFile.new
else raise “Backend type not recognized”
end
end
end

class DB
def retrieve
puts “DB#retrieve”
end
end

class MyFile
def retrieve
puts “MyFile#retrieve”
end
end

Marcelo B. wrote in post #1002280:

Hi.

By the way, these two statments are not consistent:

I need to create a class “Getter” that exposes a method “retrieve”

(where retrieve is implemented in a separate module or
class called DB)