Share This Article
The abstract factory in Ruby is an interface or class that provides a way to create families of related or dependent objects without specifying their concrete classes.
Abstract Factory is a creational, structural design pattern that provides one of the best ways to create an object. This pattern is useful when your code needs to work with various types of objects that share a common theme.
For example, you are building a vehicle assembly system where you need to create different types of vehicles like cars, trucks, vans, etc. These vehicles can be further divided into sub-categories like luxury, sports, utility, etc. The system should be able to create objects for all these sub-categories.
The Abstract Factory design pattern is one of the 20+ structural patterns described in the original Design Patterns book. It is sometimes referred to as the pattern because the abstract factory provides a library of related objects (referred to as a kit).
In Ruby, you can implement an abstract factory by using a class with static methods.
Here’s a quick example:
class WidgetFactory
def self.create(type)
if type == :button
Button.new
elsif type == :panel
Panel.new
end
end
end
The WidgetFactory#create
method is the abstract factory, and it creates different types of widgets depending on the type
argument.
Here’s how you can use it:
WidgetFactory.create(:button)
# =>Button
WidgetFactory.create(:panel)
# => Panel
The advantage of using an abstract factory is adding new widget types without changing the code.
For example:
class WidgetFactory
def self.create(type)
if type == :button
Button.new
elsif type == :panel
Panel.new
elsif type == :window
Window.new
end
end
end
Now you can create window widgets using the WidgetFactory.create(:window)
method without changing the code that uses the WidgetFactory
to create buttons and panels.
Summary
In this article, you’ve learned how to implement Ruby’s abstract factory design pattern by using a class with static methods.
You’ve also seen how to use the abstract factory to create a family of related objects without specifying their concrete classes.