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”.
Common MistakeForgetting 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: