CodeBlanks Logo Icon CodeBlanks

Factory

Learn the Factory pattern.

Factory

The Factory pattern creates instances of different classes based on a parameter. The client calls a function without knowing which class will be used.

class Dog:
    def speak(self):
        return "hav"

class Cat:
    def speak(self):
        return "miyav"

def animal_factory(kind):
    if kind == "dog":
        return Dog()
    if kind == "cat":
        return Cat()
    raise ValueError("bilinmeyen")

The Factory adds a layer between the client and the concrete class; adding a new type requires only one line of change.

Adding a new type

Adding a new type to the Factory is easy: define a new class and add a branch to the factory function. The client code does not change.

class Bird:
    def speak(self):
        return "cik"

def animal_factory(kind):
    # ... existing branches
    if kind == "bird":
        return Bird()

This supports the open-closed principle: classes are open for extension, closed for modification.

Practice Write an animal factory

Define class Dog: and class Cat:; add def speak(self): to each (Dog returns "hav", Cat returns "miyav"). Write def animal_factory(kind):: if kind == "dog": return Dog(), if kind == "cat": return Cat(), else raise ValueError("bilinmeyen"). Get an instance with a = animal_factory("dog"). Print the speak output with print(a.speak()).

Starter code

main.py
# define Dog and Cat classes (with speak method)
# write animal_factory: return Dog or Cat by kind
# raise an error on unknown kind
# get an instance with 'dog' and print the speak output

Sample solution

main.py
class Dog:
    def speak(self):
        return "hav"

class Cat:
    def speak(self):
        return "miyav"

def animal_factory(kind):
    if kind == "dog":
        return Dog()
    if kind == "cat":
        return Cat()
    raise ValueError("bilinmeyen")

a = animal_factory("dog")
print(a.speak())

Expected output

hav

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the factory call

Question
def animal_factory(kind):
    if kind == "dog":
        return ____()
    if kind == "cat":
        return Cat()
Answer
def animal_factory(kind):
    if kind == "dog":
        return Dog()
    if kind == "cat":
        return Cat()

Explanation: Dog() returns a dog instance.

2 What is the advantage of the Factory pattern?

  • It runs faster
  • The client does not know the concrete class Correct answer
  • It uses less memory
  • The code is shorter

Explanation: The Factory decouples the client from the concrete class; this makes change easier.

3 Match the Factory concepts

Term Meaning
animal_factory Produces an instance
kind parameter Sets the type
Dog() Is a concrete instance
ValueError Raised on unknown type

All lessons in Advanced