Design Patterns
Design patterns are typical solutions to common problems in software design. They are like pre-made blueprints that you can customize to solve a recurring design problem in your code.
1. Singleton Pattern
The Singleton pattern ensures that a class has only one instance and provides a global point of access to it.
- Use Case: Database connections, logging services, configuration managers.
Example (Java)
public class Database {
private static Database instance;
private Database() {
// Private constructor prevents instantiation from outside
}
public static Database getInstance() {
if (instance == null) {
instance = new Database();
}
return instance;
}
}
Example (Python)
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super(Singleton, cls).__new__(cls)
return cls._instance
s1 = Singleton()
s2 = Singleton()
print(s1 is s2) # True
2. Factory Method Pattern
The Factory Method pattern provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created. It deals with the problem of creating objects without specifying the exact class of object that will be created.
- Use Case: UI frameworks (creating buttons/dialogs for different OS), logistics (creating Trucks vs Ships).
Example (TypeScript)
interface Transport {
deliver(): void;
}
class Truck implements Transport {
deliver() {
console.log("Delivering by land in a box.");
}
}
class Ship implements Transport {
deliver() {
console.log("Delivering by sea in a container.");
}
}
class Logistics {
// Factory method logic often lives here or in subclasses
createTransport(type: "sea" | "land"): Transport {
if (type === "sea") return new Ship();
return new Truck();
}
}