Sobes.tech
Junior — Middle

Can you give examples of main design patterns and explain their application?

sobes.tech AI

Answer from AI

Main design patterns and their applications:

  • Singleton — ensures that a class has only one instance and provides a global point of access to it. Used, for example, for managing configuration or database connections.

  • Factory Method — defines an interface for creating an object but allows subclasses to alter the type of objects that will be created. Helps in creating objects without specifying the exact class.

  • Observer — allows objects to subscribe to events of another object and receive notifications about changes. Often used in GUI or event-driven systems.

  • Decorator — dynamically adds new responsibilities to objects without changing their structure. Useful for extending functionality without inheritance.

  • Strategy — defines a family of algorithms, encapsulates each one, and makes them interchangeable. Allows changing algorithms at runtime.

Example of Singleton usage in Java:

public class DatabaseConnection {
    private static DatabaseConnection instance;

    private DatabaseConnection() {
        // initialization of connection
    }

    public static synchronized DatabaseConnection getInstance() {
        if (instance == null) {
            instance = new DatabaseConnection();
        }
        return instance;
    }
}
Can you give examples of main design patterns and… - sobes.tech