lundi 28 novembre 2022

Modify functionality of Parent class without rewrite in java

Let's say I have an abstract class, called Logger:

public abstract class AbstractLogger {
public enum Levels {
    DEBUG, INFO, WARNING, ERROR
}

public void debug(String message) {
    Levels level = Levels.DEBUG;
    log(level, message);
}

public void info(String message) {
    Levels level = Levels.INFO;
    log(level, message);
}

public void warning(String message) {
    Levels level = Levels.WARNING;
    log(level, message);    }

public void error(String message) {
    Levels level = Levels.ERROR;
    log(level, message);    }

public void log(Levels level, String message) {}

}

And I also have classes that inherit this class, such as FileAppenderLogger:

public class FileAppenderLogger extends AbstractLogger {
private final Path logPath;

public FileAppender(Path logPath) {
    this.logPath = logPath;
    createLogFile();
}

private void createLogFile() {
    try {
        File logFile = new File(logPath.toString());
        if (logFile.createNewFile()) {
            System.out.println("File created: " + logFile.getName());
        } else {
            System.out.println("File already exists.");
        }
    } catch (IOException e) {
        System.out.println("An error occurred.");
        e.printStackTrace();
    }
}

@Override
public void log(Levels level, String message) {
    try {
        FileWriter myWriter = new FileWriter(this.logPath.toString());
        myWriter.write(message+"\n");
        myWriter.close();
        System.out.println("Successfully wrote to the file.");
    } catch (IOException e) {
        System.out.println("An error occurred.");
        e.printStackTrace();
    }
}

@Override
public void debug(String message) {
    super.info(message);
}

@Override
public void info(String message) {
    super.info(message);
}

@Override
public void warning(String message) {
    super.warning(message);
}

@Override
public void error(String message) {
    super.error(message);
}

}

Now, let's say I need to extend Logger to support new Log level, such as "FATAL", and also extend its children, such as FileAppenderLogger to support it, without modify any of those classes, only extend them. what could be the best practice for that (if I still want to preserve non generic methods such as ".info(String s)" or ".debug(String s))? What design pattern may I use here? I'm open for changes regard this problem. Thank you!

Aucun commentaire:

Enregistrer un commentaire