Sobes.tech
Middle

Choose a design pattern for a logging system (in DB, text file, via request)

sobes.tech AI

Answer from AI

For a logging system that can record data to different sources (database, text file, via request), the Strategy design pattern is well suited.

This pattern allows defining a family of logging algorithms, encapsulating each one, and making them interchangeable. Depending on the configuration or runtime conditions, you can choose the desired logging method without changing the client code.

Example in Java:

public interface LoggerStrategy {
    void log(String message);
}

public class FileLogger implements LoggerStrategy {
    public void log(String message) {
        // write to file
    }
}

public class DbLogger implements LoggerStrategy {
    public void log(String message) {
        // write to database
    }
}

public class QueryLogger implements LoggerStrategy {
    public void log(String message) {
        // log via query
    }
}

public class LoggerContext {
    private LoggerStrategy strategy;

    public LoggerContext(LoggerStrategy strategy) {
        this.strategy = strategy;
    }

    public void setStrategy(LoggerStrategy strategy) {
        this.strategy = strategy;
    }

    public void log(String message) {
        strategy.log(message);
    }
}

This approach ensures flexibility and extensibility of the logging system.