Design Patterns in Ruby: Picking the Right Class with a Factory
- A Different Kind of Duck Typing
- The Template Method Strikes Again
- Parameterized Factory Methods
- Classes Are Just Objects, Too
- Bad News: Your Program Hits the Big Time
- Bundles of Object Creation
- Classes Are Just Objects (Again)
- Leveraging the Name
- Using and Abusing the Factory Patterns
- Factory Patterns in the Wild
- Wrapping Up
My high school physics teacher was one of those extraordinary educators who could make even the driest of subjects come alive. It seemed that by about the second month of the school year, all of us in his Introduction to Physics class had forgotten about getting a decent grade and had moved on to a higher goal: We all wanted to do good physics. “Doing good physics” involved a lot of things—I recall careful experiments and a lot of thinking were involved—but there was one thing that a good physics student needed to avoid at all costs. There was to be no “hand waving.” Hand waving, as it was defined in my class, involved glossing over some key detail, fudging some equation, or simply assuming some fact that was not supported by experiment.
And now I have a confession to make: I have done a bit of hand waving in this book. The key detail that I have been glossing over until now is the one where your code magically knows which class to pick at some critical point. Picking the right class usually requires very little brain power: If I need a String or a Date or even a PersonnelRecord, I generally just call new on the String or Date or PersonnelRecord class and I am done. But sometimes the choice of which class to use is a critical decision. Examples of this kind of situation are easy to come by. For example, think about the Template Method pattern. When you use the Template Method pattern, you need to pick one of the subclasses—and the subclass that you pick determines which variation of the algorithm you will end up using. Will you be using a PlainReport or an HTMLReport today? Similarly, with the Strategy pattern, you must pick the correct strategy to feed to your context object: Do you need the VirginiaTaxCalculator or the NewJerseyTaxCalculator? Likewise, if you plan to proxy an object, you need to select the proxy class that does what you want.
There are a number of ways to deal with the problem of picking the right class for the circumstances, including two of the original GoF patterns. In this chapter, we will look at both of these GoF patterns: the Factory Method pattern and the Abstract Factory pattern. We will also shine our light on some dynamic Ruby techniques that will help us build factories more effectively.
So let’s get started before I incur the wrath of Mr. Malone, physics teacher extraordinaire.
A Different Kind of Duck Typing
To start our exploration of factories, let’s begin with a programming problem. Imagine that you are asked to build a simulation of life in a pond. In particular, you need to model the comings and goings of the ducks. So you sit down and write a class to model the ducks:
class Duck def initialize(name) @name = name end def eat puts("Duck #{@name} is eating.") end def speak puts("Duck #{@name} says Quack!") end def sleep puts("Duck #{@name} sleeps quietly.") end end
As you can see from this code, ducks—like most animals—eat, sleep, and make noise. But ducks also need a place to live, and for that you build a Pond class:
class Pond def initialize(number_ducks) @ducks = [] number_ducks.times do |i| duck = Duck.new("Duck#{i}") @ducks << duck end end def simulate_one_day @ducks.each {|duck| duck.speak} @ducks.each {|duck| duck.eat} @ducks.each {|duck| duck.sleep} end end
Running the pond simulation is not much of a challenge:
pond = Pond.new(3) pond.simulate_one_day
The preceding code simulates one day in the life of a three-duck pond, and it produces the following output:
Duck Duck0 says Quack! Duck Duck1 says Quack! Duck Duck2 says Quack! Duck Duck0 is eating. Duck Duck1 is eating. Duck Duck2 is eating. Duck Duck0 sleeps quietly. Duck Duck1 sleeps quietly. Duck Duck2 sleeps quietly.
Life on the pond continues idyllically until one dark day when you get a request to model a different denizen of the puddle: the frog. Now it is easy enough to create a Frog class that sports exactly the same interface as the ducks:
class Frog def initialize(name) @name = name end def eat puts("Frog #{@name} is eating.") end def speak puts("Frog #{@name} says Crooooaaaak!") end def sleep puts("Frog #{@name} doesn't sleep; he croaks all night!") end end
But there is a problem with the Pond class—right there in the initialize method you are explicitly creating ducks:
def initialize(number_ducks) @ducks = [] number_ducks.times do |i| duck = Duck.new("Duck#{i}") @ducks << duck end end
The trouble is that you need to separate out something that is changing—the specific creatures that inhabit the pond (duck or frog)—from something that is staying the same—the other workings of the Pond class. If only you could somehow excise that Duck.new from the Pond class, then the Pond class could support both ducks and frogs. This dilemma brings us to the central question of this chapter: Which class do you use?