Abstract Factory

Design patterns / Creational patterns
image

-- Products of family 1: a product is a table
-- with the function its role needs
local function new_product_a1()
  return {test_a = function()
    return "test A1"
  end}
end

local function new_product_b1()
  return {test_b = function()
    return "test B1"
  end}
end

-- Products of family 2
local function new_product_a2()
  return {test_a = function()
    return "test A2"
  end}
end

local function new_product_b2()
  return {test_b = function()
    return "test B2"
  end}
end

-- Concrete factories: tables of constructors
-- under the same keys
local factory1 = {create_a = new_product_a1,
                  create_b = new_product_b1}
local factory2 = {create_a = new_product_a2,
                  create_b = new_product_b2}

-- Client: uses the keys, never the family
local function check_factory(factory)
  local product_a = factory.create_a()
  local product_b = factory.create_b()
  return product_a.test_a() .. ", "
         .. product_b.test_b()
end

local result1 = check_factory(factory1)
-- result1 = test A1, test B1
local result2 = check_factory(factory2)
-- result2 = test A2, test B2

print("result1 = " .. result1)
print("result2 = " .. result2)


Provides an interface for creating families of objects whose interfaces are known but concrete classes are not.
Read more

The problem. A program draws its windows in two styles, light and dark. Each style needs its own button and its own menu. If the code creates them directly, it can mix a light button with a dark menu by mistake. A third style would also mean a search for every place where a button or a menu is created.

The idea. An abstract factory is an interface with one creation method for each kind of product. Each concrete factory implements it for one family. One factory creates the light button and the light menu; another creates the dark ones. The client receives a factory and creates every product through it. It never names a concrete product, so the products it gets always belong to one family. To change the whole family, you give the client a different factory.

How to read the example. There are two kinds of product, A and B. A concrete factory makes one family: one product of each kind, marked with the same number. The client receives a factory, asks it for one product of each kind and uses both. The client does not know which family it got, but the output shows it. Some languages declare no interfaces at all, but the roles stay the same.

When to use it. Use Abstract Factory when products must work together and there are several families of them, such as visual themes or operating systems. Do not use it when there is only one family. It is also not needed when the products do not depend on each other: a constructor or a Factory Method is enough.

A common mistake. Choosing this pattern while the kinds of product still change often. Each new kind adds a method to the abstract factory and to every concrete factory.