Design Patterns in Ruby: Abstract Factory
02:18 PMDevelopment, Metodologies, RubyStefano
An abstract Factory provides a common interface for creating families of related objects together.
The client object does not bother to build objects directly, but it calls the methods provided by this common interface.
Below is showed one possible implementation of an abstract Factory and its concrete Factories that implement it.
Suppose we have two categories of games as a model classes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #models.rb class Game attr_accessor :title def initialize(title) @title = title end end class Rpg < Game def description puts "I am a RPG named #{@title}" end end class Arcade < Game def description puts "I am an Arcade named #{@title}" end end |
How we can see, both models derive from a common superclass Game.
Let’s define the Factories delegate to build these objects:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #factories.rb module MyAbstractGameFactory def create(title) raise NotImplementedError, "You should implement this method" end end class RpgFactory include MyAbstractGameFactory def create(title) Rpg.new title end end class ArcadeFactory include MyAbstractGameFactory def create(title) Arcade.new title end end |
Note that we have defined the abstract factory (MyAbstractGameFactory) as a module: it defines the abstract method that must be implemented by the class that includes it.
RpgFactory and ArcadeFactory represent the two concrete factories responsible to build, respectively, Arcade and RPG games.
The code of a GameStore, that can provide games basing on the needs of the customer, will be defined as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | class GameStore def initialize(number_of_games, game_type) if game_type == :rpg title = 'Final Fantasy' game_factory = RpgFactory.new elsif game_type== :arcade title = 'Double Dragon' game_factory = ArcadeFactory.new end @games = [] number_of_games.times do |i| @games << game_factory.create("#{title} #{i+1}") end end def show_games @games.each {|game| game.description} end end |
At this point, launching the following file main.rb
1 2 3 4 5 6 7 | #main.rb require 'models.rb' require 'factories.rb' game_store = GameStore.new(2, :rpg) game_store.show_games game_store = GameStore.new(5, :arcade) game_store.show_games |
we’ll get the following output in console:
I am a RPG named Final Fantasy 1
I am a RPG named Final Fantasy 2
I am an Arcade named Double Dragon 1
I am an Arcade named Double Dragon 2
I am an Arcade named Double Dragon 3
I am an Arcade named Double Dragon 4
I am an Arcade named Double Dragon 5
At this point we can optimize our Factories in order to take advantage of the potential offered by Ruby:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | #factories2.rb class GameFactory include MyAbstractGameFactory def initialize(game_class) @game_class = game_class end def create(title) @game_class.new title end end class GameStore def initialize(number_of_games, game_type) c = Object.const_get(game_type.to_s.capitalize) game_factory = GameFactory.new(c) if game_type == :rpg title = 'Final Fantasy' elsif game_type == :arcade title = 'Double Dragon' end @games = [] number_of_games.times do |i| @games << game_factory.create("#{title} #{i}") end end def show_games @games.each {|game| game.description} end end |
As we can see, now a single concrete factory GameFactory continues to build Arcade and RPG basing on the need of the moment.
This will allow a system to be independent from the implementation of concrete objects and that the client, through the interface, to use the different product families.
Note that in both examples the definition of MyAbstractGameFactory was made only for educational purposes and was used to “simulate” in Ruby an abstract method of an abstract class.
The output generated by invoking this new GameStore is the same as seen in the previous example.
All code available in this repository on GitHub: design_patterns_in_ruby
Source code here
Previous posts from this serie:
Design Patterns in Ruby: Introduction
LusterForever.com – Cool silver charms and leather bracelets design! Totally awesome sterling silver bracelets.
Tags: design patterns, ruby

















[...] ORIGINAL POST [...]
[...] This post was mentioned on Twitter by Stefano Mancini, Dev Interface. Dev Interface said: "Design Patterns in Ruby: Abstract FactoryDesign Patterns in Ruby: Abstract Factory" – http://bit.ly/aVW2VE [...]
One thing tho – in Java (and many other static languages) factories are used to solve real problems. I don’t see the problem that the factory pattern would be solving in ruby. What i do see is that the pattern (at least in the case of this example) could be replaced with for example making the passed argument into a constant and initializing the given class dynamically. Something along the lines of “rpg”.to_s.classify.constantize.new(*args).
Just expressing my opinion here.
This design pattern is never implemented this way in Ruby, because classes *are* abstract factories. In the last code snippet, the GameFactory class is entirely unnecessary, and “game_factory.create(…)” should be replaced by “c.new(…)”.
For completeness, compare the following two code snippets and see how the “c” class itself already acts as a factory: http://pastie.org/1013930
OK, please, don’t just port over idioms from other languages. Not all of them apply. The posters before already stated why.
I’d like to expand on it: classes are objects – you can assign them to variables, stick them in hashes or other datastructures and do pretty much whatever you want with them. This makes explicit use of factory pattern (as in: not just using Class#new, which, as ddfreyne stated, already is a factory pattern) unecessary in ruby. Worse, it usually needlessly increases code complexity by a good bit.
I forgot – you have an error in your code. `@games.each {|game| game.description}` doesn’t do anything but simply return `@games`. So you probably either want to just do that or replace .each with .map.
@Tanel, @Denis, @Apeiros, thanks for your comments.
My examples are very connected to the original GoF pattern and probably they lack a final optimization (for example that suggested by Tanel or Denis) that confirms last Apeiros comment (explicit use of factory pattern can be unecessary in Ruby).
Take a note that you both assume to retrieve the game class just manipulating the symbol passed as argument (c = Object.const_get(game_type.to_s.capitalize); but maybe I could have passed something like :roleplaying, so I’ve keep the factory for completeness.
@Apeiros, the code works for me: @games.each {|game| game.description} just calls the description method of the game that puts “I am a RPG named Final Fantasy” and so on.
Even when just passing a symbol such as :roleplaying that maps to a class, there is no need for a separate factory; the class itself (provided that it is not nil) can be used as a factory.
Your #description method is a misnomer: its name suggests that it returns the game description, rather than printing the name. A better name would be #show or #print instead.
The book “Design Patterns in Ruby” by Russ Olsen does a good job of explaining the different (and often much simpler) approaches to implementing Gang of Four patterns that are available to you when using a dynamic language like Ruby. Well worth a read.
Thanks Kerry for your comment.
Please see my previous comment here
http://blog.devinterface.com/2010/06/design-patterns-in-ruby-introduction/comment-page-1/#comment-488
Worth noting that you don’t really need an Abstract Factory in this example because you’re only creating a single type of object – the factory method pattern would be just as good (i.e. Game.create(sym) ). Abstract Factory is mainly intended for when you need to create suites of objects.
Just using MyClass#new isn’t always appropriate though. Although you _can_ override new’s behavior – you wouldn’t necessarily want to. Factory methods provide you the flexibility to:
* return a subtype (or in ruby’s case any type of) object
* not return a new object on every invocation
* give a name to a particular method of constructing an object
* construct an object given different arguments
Although you _could_ get #new to do these, I think it would be a mistake to do so. So they still have a place in ruby.
I’d stick to inheritance to create an abstract class, rather than to a module.
I mean, I’d make MyAbstractGameFactory the superclass of RpgFactory and ArcadeFactory classes. Is there any reason why you did choose a module?
Ruby doesn’t have abstract and you don’t need to throw an exception – method_missing will throw it for you anyway.
The original Go4 book was said to be an attempt to overcome the limitations of C++, and that carried through into Java very well because Java was an attempt to simplify C++ originally.
You don’t need abstract factories in Ruby because of the dynamic nature of the language. There is no concept of Abstract in the language. You don’t even need classes – there’s a school using what they call “naked objects” where you place methods directly onto objects without defining classes at all.
game = Object.new
def game.title
@title = ‘Final Fantasy’
end
or something like
class Game
attr_reader :description
def initialize(game_type, title)
self.send game_type
end
private
def rpg
@description = ‘Final Fantasy’
end
def arcade
@description = ‘Double Dragon’
end
end
or even use lambda functions and dynamic method definition to meet your needs.
You can also do things with method_missing. There’s no need for this particular pattern. Ruby requires a different approach.
Similarly the need in Java for creating interfaces for everything so that you can easily decouple the concrete implementation class isn’t there either – the class has the method or it doesn’t.
please let me ask a stupid question. does STI (Single table inheritance) belongs to design pattern?
I like your fantastic blog!
Do you have a contact, I would love to ask you something?
Artik