CodeBlanks Logo Icon CodeBlanks

Summary - Design patterns

Combine Singleton, Factory and Strategy to write a payment system.

Summary - Design patterns

In this group you learned five core design patterns. Singleton gives a single instance, Factory picks a class, Strategy is a callable algorithm, Observer is subscription notification, Decorator is wrapper extension.

# Singleton + Factory + Strategy combined
reg = Config()  # Singleton
strategy = payment_factory("credit")  # Factory
print(strategy(100))  # Strategy called

In the final step you will combine three patterns to write a payment system.

Practice Payment system

Define class Config: (Singleton pattern): add _instance = None, method def __new__(cls): does if cls._instance is None: cls._instance = super().__new__(cls) and return cls._instance. Function def credit_pay(amount): does return f"kredi: {amount}". Function def debit_pay(amount): does return f"banka: {amount}". Function def payment_factory(name): does if name == "credit": return credit_pay, if name == "debit": return debit_pay. Get an instance with cfg = Config(). Pick a strategy with strategy = payment_factory("credit"). Print the payment with print(strategy(100)).

Starter code

main.py
# define Config class (Singleton: _instance, __new__)
# define credit_pay and debit_pay functions (Strategy)
# write payment_factory (Factory: returns strategy by name)
# get a Config instance, pick 'credit' strategy and print the payment

Sample solution

main.py
class Config:
    _instance = None
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

def credit_pay(amount):
    return f"kredi: {amount}"

def debit_pay(amount):
    return f"banka: {amount}"

def payment_factory(name):
    if name == "credit":
        return credit_pay
    if name == "debit":
        return debit_pay

cfg = Config()
strategy = payment_factory("credit")
print(strategy(100))

Expected output

kredi: 100

Questions and answers

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

1 Which one guarantees a single instance?

  • Factory
  • Singleton Correct answer
  • Strategy
  • Observer

Explanation: Singleton ensures a class has only one instance.

2 Match the group tools

Term Meaning
Singleton Single instance
Factory Class pick
Strategy Callable algorithm
Observer Subscription

All lessons in Advanced