Introduction to the Factory Method Pattern in Ruby
Introduction to the Factory Method Pattern
Welcome back! So far, you’ve learned about the Singleton Pattern and have seen how it ensures a class has only one instance with a global access point. Now, we’re moving on to another essential creational design pattern: the Factory Method Pattern. This pattern is all about creating objects in a much more flexible way than direct instantiation.
What You'll Learn
In this lesson, you'll explore the Factory Method Pattern in Ruby. We'll cover the following key points:
- Understanding the Factory Method Pattern: Learn about the core concepts and when to use this pattern.
- Implementing a Factory Method: Discover how to create your own factory methods to instantiate different types of objects in Ruby.
- Flexibility and Extensibility: See how the Factory Method Pattern allows your code to handle new object types with ease using Ruby’s dynamic nature.
Here's a glimpse of the code you’ll be working through:
document.rb file that defines the interface for product (Document) and concrete products (WordDocument, ExcelDocument):
document_creator.rb file that defines the DocumentCreator, responsible for creating all types of documents:
main.rb file that demonstrates the usage of the Factory Method Pattern:
This snippet demonstrates a simple implementation of the Factory Method Pattern using different document types. Let's break down the code and understand how the Factory Method Pattern works in practice:
- Document: A base class representing a document interface with a method
openthat raises an exception if not implemented. This class defines the common behavior for all document types. Note: In Ruby, theDocumentclass acts as a "duck-typed interface." This means it defines a common method (open) that all subclasses are expected to implement. While Ruby doesn’t enforce interfaces like Java or C#, raising aNotImplementedErrorserves as a runtime safeguard to ensure the method is overridden in subclasses.- WordDocument and ExcelDocument: Concrete classes that implement the
Documentinterface with specificopenmethods for Word and Excel documents, respectively.
- WordDocument and ExcelDocument: Concrete classes that implement the
- DocumentCreator: A single class responsible for creating any type of document. The
create_documentmethod instantiates the appropriate document object based on the input type parameter. TheDocumentCreatorclass encapsulates the logic for deciding which type of document to create. By centralizing this decision-making, the class shields the rest of the application from needing to know the specifics of each document type. This decoupling means the client code focuses solely on using the returned objects rather than worrying about their creation.
