abstract factory pattern

The Abstract Factory Pattern is a creational design pattern that provides an protocol for creating families of related or dependent objects without specifying their concrete classes. An abstract factory pattern is often used when a system must be independent of the way the objects it creates are produced.

The abstract factory pattern is used to provide a client with a set of related objects, but without specifying their concrete classes. The client uses the abstract factory to create the objects, which are then used to accomplish some task.

Here is an example of how to use the abstract factory pattern in Swift:

protocol AbstractFactory {
    func createProductA() -> AbstractProductA
    func createProductB() -> AbstractProductB

protocol AbstractProductA {
    func operationA()

protocol AbstractProductB {
    func operationB()

class ConcreteFactory1: AbstractFactory {
    func createProductA() -> AbstractProductA {
        return ConcreteProductA1()

    func createProductB() -> AbstractProductB {
        return ConcreteProductB1()

class ConcreteProductA1: AbstractProductA {
    func operationA() {
        print("ConcreteProductA1 operationA")

class ConcreteProductB1: AbstractProductB {
    func operationB() {
        print("ConcreteProductB1 operationB")

// Client
let factory = ConcreteFactory1()
let productA = factory.createProductA()
let productB = factory.createProductB()

In this example, the AbstractFactory protocol defines the interface for creating AbstractProductA and AbstractProductB objects. The ConcreteFactory1 class is an implementation of the AbstractFactory protocol that creates concrete instances of ConcreteProductA1 and ConcreteProductB1 classes. The Client code uses the ConcreteFactory1 to create AbstractProductA and AbstractProductB objects, and then calls their operations.