drawAbstract Factory

Description

Abstract Factory is a creational design pattern that allows you to create similar objects without specifying their classes. It is the equivalent of the Strategy pattern with regarding object creation.

Problem

We want to create code to operate a virtual bar. We will serve various types of alcohol in our bar. The instructions for preparing each drink will be the same and will consist of the following steps:
  • prepare glass
  • add alcohol
  • add additions
Below is an example code that will allow us to create our drinks.

class Drink
  attr_reader :glass, :alcohol, :additions

  def initialize(klass)
    # Factory is an implementation of the specific drink
    factory = klass.new

    @glass = factory.prepare_glass
    @alcohol = factory.add_alcohol
    @additions = factory.add_additions
  end
end
We have already written the main code that will allow us to create the drink. Now we need to create implementations for a specific drink.

class WhiskyFactory
  def prepare_glass
    Glass.new(size: 200)
  end

  def add_alcohol
    Whisky.new
  end

  def add_additions
    [Ice.new, Ice.new, Lime.new]
  end
end
Let’s also create a factory that will allow us to create a shot of vodka.

class VodkaFactory
  def prepare_glass
    Glass.new(size: 40)
  end

  def add_alcohol
    Vodka.new
  end

  def add_additions
    nil
  end
end
We have almost everything ready. Let’s add the classes that are in individual factories.

# Real implementations of those classes are not important for this example.
class Vodka; end
class Whisky; end
class Ice; end
class Lime; end

class Glass
  attr_reader :size

  def initialize(size: nil)
    @size = size
  end
end

class Book
  include Visitable

  attr_accessor :title, :price

  def initialize(title:, price:)
    @title = title
    @price = price
  end
end
Now that everything is ready, we can easily create our drinks.

vodka = Drink.new(VodkaFactory)
whisky = Drink.new(WhiskyFactory)

vodka.glass.size # => 40
If you have learned the Strategy pattern before, you should have no problem understanding this pattern because they are very similar. The difference between them is that the Abstract Factory pattern is used to create similar objects, and the Strategy is used to create certain structures.