Design Patterns in Ruby : The Factory Method

2
Categories: Design Patterns
Posted on: 26th April 2009 by: kitallis

This is an article series on implementing programming Design Patterns in Ruby. This is the second part of the series and here’s a link to the last article on the Template Design Pattern.

The Factory Method Pattern

I have to this say this, but Wikipedia has a pretty good explanation and a Ruby implementation for this Creational Pattern, so I’d be focusing mainly upon the general idea of why this pattern is similar to the Template Method pattern and explain some of its defined variants.

What is it?

It is a Creational design pattern : defining how created objects should be mechanised as per the pattern as chances are there might be design problems with bad object control.

When is it needed?

It’s all about picking the right class. It’s pretty much like the Template Method pattern. In the Template Method pattern there was a generic portion which was stored in a base class and the other fill-in-the blanks were controlled by the subclasses and the Template method drove certain methods so that they needn’t be explicitly called. Here, with the Factory Method those subclasses determine what objects to be created. So the Factory Method is for creating objects as Template Method was for driving an algorithm.

How is it done?

Here’s my dummy implementation for the Factory Method pattern.

module Factory
  def draw
     raise NotImplementedError, "You need to call this method, brotha"
  end
end

class Circle
 include Factory
 def draw
   # Clear Screen
   # Draw Circle
 end
end

class Square
 include Factory
   def draw
     # Clear Screen
     # Draw Square
   end
end

class Tetrahedron
  include Factory
  def draw
    # Clear Screen
    # Draw Square
  end
end

class RandomShape
  include Factory
    def draw
      # Clear Screen
      # Draw any shape apart from the above three
    end
end

class CreateShape
  def self.CallShapes(shape)
    case(shape)
      when "Circle"
        Circle.new
      when "Square"
        Square.new
      when "Tetrahedron"
        Tetrahedron.new
    else
      RandomShape.new
    end
  end
end

More precisely, the Shape module is for defining the Draw method which raises a predefined NotImplementedError exception object. Circle, Square and Tetrahedron are the subclasses which call the Shape module and are called by the Factory Method – CallShapes for creating objects out of them to be selected as per the user call.

This pattern is used when a class (theCreator) does not know beforehand all the subclasses that it will create. Instead, each subclass (the Concrete Creator) is left with the responsibility of creating the actual object instances.
The example shown here is specifically a Parametrized Factory Method, that takes in certain parameters from the user and creates objects accordingly.

Abstract Factory Method can pretty much be understood by this UML diagram

Factory Method UML

(Courtesy : Design patterns in Ruby )

The basic idea behind Abstract Factory Methods are to form a group of factories that are compatible with each other. According to the diagram, there are Two Factories encapsulated by one single Abstract factory and each concrete factory produces its set of compatible products. And that’s pretty much what Abstract Factory Methods are.

Taking an example from the Book, the ActiveRecord library uses a form of this kind of pattern.
ActiveRecord has an adapter class for each different kind of database that it uses like MySQL, Oracle. To set up the connection the user name, password, and a string containing the name of the adapter that ActiveRecord uses is supplied. So we enter ‘mysql’ if we want to talk to a MySQL database and so on. To accomplish this a Base class is present that has no adapter related code.
But there are Subclasses that modifying the Base code, that is, each adapter adds a method that creates its specific type of connection to
the Base class.

class Base
# Lots of non-adapter-related code removed...
end

class Base
  def self.mysql_connection(config)
 # Create and return a new MySQL connection, using
 # the user name, password, etc. stored in the
 # config hash...
  end
end

class Base
  def self.oracle_connection(config)
 # Create a new Oracle connection...
  end
end

If a structured object creation method like the Factory Method in a class is not implemented, we might end up creating methods for each new object we want to create.

References

[1] Wikipedia

[2] Programmers Heaven

Design Patterns in Ruby : The Template Method

4
Categories: Design Patterns
Posted on: 8th March 2009 by: kitallis

Just before a month ago I was sweating out, playing away with my small little Ruby programs which were surely not pieces of code you’ll want to read and learn with. Now just after my fifteen day brawl with the Design Patterns, I find myself a totally revamped programmer.
This is my new article series which would cover a few of the popular programming Design Patterns in software engineering devised by the GoF. I would be starting off with some basic Design Patterns and then move onto Ruby specific patterns based upon the book “Design Patterns In Ruby” by Russ Olsen.

The Design Patterns that’ll be explained are :

1. The Template Method (explained here)
2. The Factory Method

(They will be updated as the series expands)
You can Subscribe to my Blog Feeds for constant updates on the articles or you can follow me on www.twitter.com/kitallis
This is the base article for the series and you can always look back at this as an archive for others.

Prerequisites would be, a knowledge of Ruby’s Object Oriented features and a belief that this would actually help you get better.
These articles would follow a simple pattern of explaining the design pattern, disadvantages without it and improving with it. If you don’t quite get what I’m talking about, you might want to take a look at this.

The Template Method Pattern

When is it needed?
The Design patterns are a way of solving a problem in a particular way and is in no way related to reducing the complexity of the algorithm.
The basic problem on which this DP is implemented upon is a varying piece of code mixed in with the part that remains static. So we would be separating the code that stays the same (probably the algorithm) with the piece of code that is dynamic (probably the processing data).

How can we do it?
By separating and encapsulating the common entities into a subclass and the changing entities/behaviour into derived classes and thereby allowing the common behaviour to not repeat itself.
More specifically, building an abstract base class with a skeletal method (template method) that’d control the part that needs to vary by making calls to the Abstract Method whose actual control is further provided by the subclasses.
Even more strictly, this is an actual application of the Template Method Pattern in the ControlTier project which defines an application installation procedure
(other details are unnecessary here)

(Courtesy : ControlTier Wiki)

The Template Methods residing in the Abstract class are ‘driving’ certain Operations and the subclasses are actually implementing those Operations. So here, InstallPackage is the Template Method which defines all usable methods and zip is the concrete subclass which calls methods it requires.

So, the quick advantages we get are :

1. We can expand to more subclasses even if they require a varying algorithm for the methods defined

2. The algorithm is separated from the static definitions and initialisations

This is my dummy code for the pattern

class Package  # this is the abstract base class
 
  def initialize
  #
  end
 
  def InstallPackage  # this is the template method
 
  create
  installDependencies
  prepare
  get
  extract
  finish
 
  end
 
  def installDependencies
  #
  end
 
  def prepare
  #
  end
 
  def get
  #
  end
 
  def extract
  #
  end
 
  def finish
  #
  end
 
  end
 
class Zip < Package  # this is the concrete subclass
 
  def create
  #
  end
 
  def extract
  #
  end
 
end

And it might be called this way

z = Zip.new
 
z.InstallPackage # calling the template method from the subclass

GOF describes a Hook Method
These are basically just virtual methods which may or may not have code inside them in base classes.
They are a way of telling the concrete subclasses that “either use the default implementation in the abstract class or override it for some varying algorithm and do something different”

Implementations without this pattern could be

class Package
 
  def initialize
  end
 
  def get_method(type)
  end 
 
  if type == "Zip" 
 
  # create algorithm
  # extract algorithm
 
  elsif #some other type
 
  end
 
end

which could be amazingly hard to expand for large pieces of code.
I’m obviously not that experienced a programmer to write hugely scalable projects but I find it a good habit to adopt patterns even while writing smaller snippets.