Commonly Used Design Patterns in OOP
What Are Design Patterns?
- Design patterns are reusable solutions to common software design problems.
- Their purpose is to provide best practices for creating scalable, maintainable, and flexible code.
- Their benefit is that they save time, improve communication between developers, and avoid reinventing the wheel.
Key Patterns in the IB Syllabus
Singleton Pattern
- Goal: Ensure only one instance of a class exists in the system.
- When Used:
- Database connections
- Configuration settings
Java:
class Database {
private static Database instance;
private Database() {} // private constructor
public static Database getInstance() {
if (instance == null) {
instance = new Database();
}
return instance;
}
}Think “only one manager in charge”.
Forgetting to make the constructor private → multiple instances can be created.
Factory Pattern
- Goal: Create objects without exposing the creation logic to the client.
- When Used:
- When many subclasses exist and the client shouldn’t need to know which to use.
Python:
class ShapeFactory:
def get_shape(self, shape_type):
if shape_type == "circle":
return Circle()
elif shape_type == "square":
return Square()Think “ordering food from a restaurant kitchen”: you don’t need to know how it’s cooked.
Hardcoding too many if-else statements → reduces flexibility.
Observer Pattern
- Goal: Define a one-to-many relationship so when one object changes, others are automatically notified.
- When Used:
- Event-driven systems (e.g., GUI buttons, notifications)
A Weather Station notifies multiple display screens when temperature updates.
Think “YouTube subscribers”: if the creator uploads, all subscribers get notified.
Forgetting to detach observers → leads to memory leaks or unwanted notifications.
Why Patterns Matter
- Solve recurring problems in software development.
- Make designs easier to communicate among developers.
- Encourage reusability and scalability
- Be ready to name and explain at least three patterns (Singleton, Factory, Observer).
- Use real-world analogies (e.g., restaurant, YouTube, manager).
- Link patterns to OOP principles: abstraction, encapsulation, reusability
- Singleton → only one instance.
- Factory → controlled object creation.
- Observer → automatic updates across multiple objects