Sobes.tech
Junior — Middle

Can you explain the concept and application of the factory method in design patterns?

sobes.tech AI

Answer from AI

The Factory Method is a design pattern that defines an interface for creating an object but allows subclasses to decide which class to instantiate.

This is useful when you want to delegate the creation of objects to subclasses so that you don't tightly couple your code to specific classes.

Example in Swift:

protocol Product {
    func use()
}

class ConcreteProductA: Product {
    func use() {
        print("Using product A")
    }
}

class ConcreteProductB: Product {
    func use() {
        print("Using product B")
    }
}

protocol Creator {
    func factoryMethod() -> Product
}

class CreatorA: Creator {
    func factoryMethod() -> Product {
        return ConcreteProductA()
    }
}

class CreatorB: Creator {
    func factoryMethod() -> Product {
        return ConcreteProductB()
    }
}

// Usage
let creator: Creator = CreatorA()
let product = creator.factoryMethod()
product.use()  // Outputs: Using product A

Thus, the Factory Method allows creating objects without specifying the exact class, which makes the code easier to extend and maintain.

Can you explain the concept and application of the… - sobes.tech