Ty decorator pattern is a powerful design pattern in software especially useful when you need to add logging to service methods with out altering their original code. This accerach is especially useful when youu need to add logging to service methods with out altering their source ce code, ensuring clean and maintainable codebases.

Understanding thee Decorator Pattern

Te decorator pattern implemenves creating a wrapper class that implementts the same interface as the original service. This wrapper delegates calls to thee original service but adds additional behavor - such as logging - before or after the methode execution.

Implementing Logging with the Decorator Pattern

Suppose you have a service interface:

public interface DataService {
 void fetchData();
}

Yu can cree a concrete implementation:

public class RealDataService implements DataService {
 @Override
 public void fetchData() {
 // Fetch data from a database or external API
 }
}

Next, create a decorator class that adds logging:

public class LoggingDataServiceDecorator implements DataService {
 private final DataService wrappedService;

 public LoggingDataServiceDecorator(DataService service) {
 this.wrappedService = service;
 }

 @Override
 public void fetchData() {
 System.out.println("Fetching data started.");
 wrappedService.fetchData();
 System.out.println("Fetching data completed.");
 }
}

Using thee Decorator

To add logging, instantiate thee decorator with your existing service:

DataService service = new RealDataService();
DataService loggedService = new LoggingDataServiceDecorator(service);

// Now, calling fetchData will include logging
loggedService.fetchData();

Výhody of te Decorator Pattern

  • Enhances existing funkcionality with out modififying original code
  • Promotes code reuse and separation of concerns
  • Facilitates adding multiplelaiers of behavior dynamically

Using thee decorator pattern for logging is an elegant solution that maintains clean code and adheres to te thon-closed principla, making your applications easier to extend and maintain.