Home > Articles > Programming > Ruby

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Wrapping Up

Wrapping Up

In this chapter, we looked at the two GoF factory patterns, both of which are techniques for answering the question “Which class?”

The Factory Method pattern involves the application of the Template Method pattern to object creation. True to its Template Method roots, this pattern says to just leave the “which class” question to be answered by a subclass. We saw that we could use this pattern to build a generic Pond class that knows all about environmental simulations but leaves the choice of the specific plant and animal classes to its subclass. We therefore create subclasses with names like DuckWaterLilyPond and FrogAlgaePond, which in turn fill in the factory methods with implementations that create the appropriate kinds of objects.

The Abstract Factory pattern comes into play when you want to create compatible sets of objects. If you want to ensure that your frogs and algae don’t end up in the same habitat as your tigers and trees, then create an abstract factory for each valid combination.

The key thing that we discovered in this chapter is how both of these patterns morphed in Ruby’s dynamic environment—specifically, how they became much simpler. While the GoF concentrated on inheritance-based implementations of their factories, we can get the same results with much less code by taking advantage of the fact that in Ruby, classes are just objects. In Ruby we can look up classes by name, pass them around, and store them away for future use.

Looking ahead, the next pattern that we will examine is the Builder pattern, which also produces new objects but is much more tightly focused on constructing complex objects than on picking the right class. But we are by no means finished with the question of how to produce the right objects for the problem at hand. In Chapter 17, we will look at meta-programming, a technique for customizing your classes and objects at runtime.

  • + Share This
  • 🔖 Save To Your Account