Junior — Middle
Can you give examples of common design patterns in software systems?
sobes.tech AI
Answer from AI
Common design patterns help create flexible, maintainable, and extendable systems. Here are some examples:
- Singleton — ensures a class has only one instance and provides a global point of access to it.
- Factory Method — defines an interface for creating an object but allows subclasses to alter the type of objects that will be created.
- Observer — allows objects to subscribe to events of another object and receive notifications of changes.
- Decorator — dynamically adds responsibilities to objects by wrapping them.
- Strategy — defines a family of algorithms, encapsulates each one, and makes them interchangeable.
Example of the Singleton pattern in Java:
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}