Sobes.tech
Junior — Middle

Can you give examples of common patterns in object-oriented design?

sobes.tech AI

Answer from AI

Object-oriented design often uses the following patterns:

  • Singleton — guarantees that 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 about changes.
  • Decorator — dynamically adds responsibilities to objects by wrapping them in other objects.
  • 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;
    }
}