Share This Article
This tutorial will show how to integrate the Factory Pattern in Ruby.
Factory Pattern is the creational design pattern in Ruby that defines an interface for creating objects and lets the classes that implement the interface decide which classes to instantiate.
Factory Pattern is also known as Virtual Constructor.
The Factory Pattern is helpful in a situation that requires the creation of different sub-types of objects from the same superclass.
How to Implement Factory Pattern in Ruby
Let’s understand the Factory Pattern with an example.
Assume that you are working on an e-commerce website. The website sells many products, such as books, clothes, electronic items, etc.
For this example, let’s focus on electronic items. Electronic items have different attributes such as price, color, size, weight, etc.
You can create a superclass named ElectronicItem and subclasses named Book, Clothes, etc., inherited from the superclass.
These subclasses have different methods to calculate the price based on their attributes.`
Now, let’s say a customer wants to buy an electronic item. The customer will first select the item type (book, clothes, etc.), the attributes (color, size, weight, etc.), and quantity.
Based on the selection, you need to calculate the price and show it to the customer.
In the traditional approach, you must write an if-else or switch statement to create an instance of the appropriate subclass.
Example:
class ElectronicItem
def self.create(type)
if type == 'book'
Book.new
elsif type == 'clothes'
Clothes.new
end
end
end
class Book < ElectronicItem
end
class Clothes < ElectronicItem
end
item1 = ElectronicItem.create('book')
item2 = ElectronicItem.create('clothes')
In the above example, the create method is a factory method. The factory method is the method that is responsible for creating objects.
The create method has a type parameter used to create an instance of the appropriate subclass.
The type parameter can be input from the user or another source.
Advantages of Factory Pattern
The advantages of using the Factory Pattern are as follows:
- First, it isolates the dependencies between the classes.
- Second, it allows you to change the implementation of a class without changing the client code.
- Third, it will enable you to create objects without specifying their concrete classes.
When to use Factory Pattern
It would help if you used the Factory Pattern when all of the following conditions are met:
- You have to create different sub-types of objects from the same superclass.
- It would help if you had a simple way to create these sub-type objects.
Summary
In this article, you’ve learned about the Factory Pattern and how to implement it in Ruby. You’ve also known the benefits and when to use the Factory Pattern.