Sobes.tech
Junior — Middle

What results are created when using the factory pattern?

sobes.tech AI

Answer from AI

The Factory design pattern is used to create objects without specifying the exact class of the object that will be created. As a result of applying this pattern, objects are encapsulated within a factory method or class, which makes it easy to change the type of objects created without modifying client code.

For example, using a factory, you can obtain different subclasses of a single interface depending on the parameters passed to the factory.

Example in Python:

class Animal:
    def speak(self):
        pass

class Dog(Animal):
    def speak(self):
        return "Woof"

class Cat(Animal):
    def speak(self):
        return "Meow"

class AnimalFactory:
    @staticmethod
    def create_animal(animal_type):
        if animal_type == "dog":
            return Dog()
        elif animal_type == "cat":
            return Cat()
        else:
            return None

# Usage
animal = AnimalFactory.create_animal("dog")
print(animal.speak())  # Outputs: Woof

Thus, the result of using the factory pattern is the creation of objects of the desired type, hiding the details of their creation and allowing easy extension and modification of the created objects.