Skills101

AdvancedSoftware Engineering · Lesson 10 of 13 · Updated ·

Design Patterns — Singleton, Factory, Builder, Adapter, Decorator, Observer and Strategy

Every developer meets the same problems again and again: "only one object of this class may exist", "I must create objects without knowing their exact class", "many screens must update when the data changes". A design pattern is a named, tested solution to such a recurring problem. It is not a library you install — it is an idea for how to arrange classes, which you write yourself each time.

The famous catalogue is the 1994 book Design Patterns by Gamma, Helm, Johnson and Vlissides, called the Gang of Four (GoF). It describes 23 patterns in three groups.

The three Gang of Four groups: creational patterns decide how objects are created (Singleton, Factory Method, Builder), structural patterns decide how objects are combined (Adapter, Decorator, Facade), behavioural patterns decide how objects talk (Observer, Strategy, Command)

GroupQuestion it answersPatterns in this lesson
CreationalHow are objects created?Singleton, Factory Method, Builder
StructuralHow are objects combined?Adapter, Decorator
BehaviouralHow do objects communicate?Observer, Strategy

Patterns help in two ways: they give a shared vocabulary ("use an observer here" says a lot in three words), and they apply the SOLID principles from the previous lesson.

1. Singleton (creational)

Problem: exactly one instance must exist, such as the app's configuration or a connection pool, and everybody must reach the same one.

class Config:
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._instance.settings = {'theme': 'light'}
        return cls._instance

a = Config()
b = Config()
b.settings['theme'] = 'dark'
print(a is b, a.settings['theme'])
True dark

__new__ returns the stored object instead of creating a new one, so a and b are the same object. Caution: a singleton is global state in disguise. It makes unit tests harder (state leaks between tests) and hides dependencies. Many teams prefer creating one object at startup and passing it in (dependency injection). In multi-threaded Java, a lazy singleton also needs care so that two threads don't create two instances.

2. Factory Method (creational)

Problem: the code needs an object, but which class to create depends on input or configuration. Instead of if/else blocks spread across the program, one place decides.

class UpiPayment:
    def pay(self, amt):
        return f'UPI paid Rs {amt}'

class CardPayment:
    def pay(self, amt):
        return f'Card paid Rs {amt}'

class WalletPayment:
    def pay(self, amt):
        return f'Wallet paid Rs {amt}'

def payment_factory(kind):
    classes = {'upi': UpiPayment, 'card': CardPayment, 'wallet': WalletPayment}
    if kind not in classes:
        raise ValueError(f'unknown payment type: {kind}')
    return classes[kind]()

for kind in ['upi', 'card']:
    print(payment_factory(kind).pay(499))
UPI paid Rs 499
Card paid Rs 499

The checkout code calls payment_factory(kind).pay(...) and never names a concrete class. Adding net banking means one new class and one dictionary entry. (Strictly, GoF's Factory Method lets subclasses decide which class to create; the function above is the simpler simple factory, which is what most interview answers mean.)

3. Builder (creational)

Problem: an object has many optional parts — a pizza order, an HTTP request, an SQL query. A constructor with ten parameters is unreadable. A builder sets the parts step by step and then builds.

class QueryBuilder:
    def __init__(self, table):
        self.table, self.wheres, self.order = table, [], None

    def where(self, cond):
        self.wheres.append(cond)
        return self                      # returning self allows chaining

    def order_by(self, col):
        self.order = col
        return self

    def build(self):
        sql = f'SELECT * FROM {self.table}'
        if self.wheres:
            sql += ' WHERE ' + ' AND '.join(self.wheres)
        if self.order:
            sql += f' ORDER BY {self.order}'
        return sql

print(QueryBuilder('students').where('cgpa > 8').where("city = 'Pune'").order_by('name').build())
SELECT * FROM students WHERE cgpa > 8 AND city = 'Pune' ORDER BY name

Java's StringBuilder, and the .builder() methods generated by the Lombok library, follow this idea.

4. Adapter (structural)

Problem: two pieces of code should work together but their interfaces don't match — like a travel plug adapter. Your app expects send(phone, text), but the new SMS provider's library offers push_message(payload).

class NewSmsApi:                          # third-party code we cannot change
    def push_message(self, payload):
        return f"sent '{payload['body']}' to {payload['to']}"

class SmsAdapter:                         # looks like what our app expects
    def __init__(self, api):
        self.api = api
    def send(self, phone, text):
        return self.api.push_message({'to': phone, 'body': text})

sender = SmsAdapter(NewSmsApi())
print(sender.send('98xxxxxx10', 'Class at 6 pm'))
sent 'Class at 6 pm' to 98xxxxxx10

The rest of the app is unchanged. If the provider is replaced again, only a new adapter is written.

5. Decorator (structural)

Problem: add responsibilities to an object without changing its class and without making a subclass for every combination (milk, sugar, milk + sugar, …). A decorator wraps an object and has the same interface.

class Tea:
    def cost(self):
        return 20
    def name(self):
        return 'tea'

class Extra:
    def __init__(self, drink, label, price):
        self.drink, self.label, self.price = drink, label, price
    def cost(self):
        return self.drink.cost() + self.price
    def name(self):
        return f'{self.drink.name()} + {self.label}'

order = Extra(Extra(Tea(), 'ginger', 5), 'elaichi', 7)
print(order.name(), '=', order.cost())
tea + ginger + elaichi = 32

Two wrappers give tea + ginger + elaichi without a GingerElaichiTea class. Java's new BufferedReader(new FileReader(...)) is the same pattern. (Python's @decorator syntax for functions is related but is a language feature, not exactly the GoF pattern.)

6. Observer (behavioural)

Problem: when one object changes, many others must be told, and the changing object should not need to know who they are. Also called publish–subscribe.

Observer pattern: a cricket scoreboard subject keeps a list of observers; when the score changes it calls update on each one, here a mobile app, a TV ticker and a website

class ScoreBoard:                          # the subject
    def __init__(self):
        self.observers = []
    def subscribe(self, fn):
        self.observers.append(fn)
    def set_score(self, runs, wickets):
        for notify in self.observers:
            notify(f'{runs}/{wickets}')

board = ScoreBoard()
board.subscribe(lambda s: print('App   :', s))
board.subscribe(lambda s: print('Ticker:', s))
board.set_score(152, 3)
App   : 152/3
Ticker: 152/3

Button click listeners, event emitters in Node.js and notifications in apps are observers. Adding a new display means subscribing one more function; the scoreboard code does not change.

7. Strategy (behavioural)

Problem: there are several ways (algorithms) to do one job, and the choice is made at run time — sort by price or by rating, calculate delivery charges by distance or by weight. Put each algorithm behind the same interface and pass the chosen one in. The offers example in the SOLID lesson was a strategy. In Python, even a plain function can be a strategy:

products = [('pen', 10, 4.1), ('bag', 799, 4.6), ('book', 250, 4.8)]
strategies = {
    'cheapest': lambda p: p[1],
    'top rated': lambda p: -p[2],
}
for name, key in strategies.items():
    print(name, [p[0] for p in sorted(products, key=key)])
cheapest ['pen', 'book', 'bag']
top rated ['book', 'bag', 'pen']

8. How to talk about patterns in an interview

  • State the problem first, then the pattern: "Several displays need score updates without the scoreboard knowing them, so I'd use Observer."
  • Name a real place you have seen it: listeners in Android or JavaScript, StringBuilder, Spring beans (singletons by default).
  • Mention the trade-off. Patterns add classes; using them where there is no recurring problem is over-engineering.

Common mistakes

  • Thinking a pattern is a ready-made library. It is a design idea you implement.
  • Using Singleton for everything as a convenient global variable.
  • Confusing Adapter (changes an interface to match another) with Decorator (keeps the same interface and adds behaviour).
  • Confusing Strategy (the caller picks one algorithm) with Observer (one event, many listeners).
  • Forcing patterns into small programs where a simple function would do.

Quick recap

  • GoF: 23 patterns in three groups — creational, structural, behavioural.
  • Singleton: one shared instance (use sparingly). Factory: one place decides which class to create. Builder: complex objects step by step.
  • Adapter: makes an incompatible interface fit. Decorator: wraps an object to add behaviour.
  • Observer: notify many subscribers of a change. Strategy: swap algorithms at run time.

Practice what you learned

📝 Quiz: Design Patterns5 questions · instant answers & explanations · +10 XP · counts towards your free certificateTake the quiz →