Table of Contents
Ez a dekorator mintata i a powerful design sample n n software that allows developers to add new functionality to extenciing objects with out modifying their origing their code. This approcach i esspecialy useful when youn needd to logging to service methods with altering their source code, ensuringlaben an an d maintainable de cobis.
Understanding the Decorator Mintan
Ez a dekorator mintaton involves creating a wrapper class that implements the same interface a s the original service. Tiss wrappep delegates calls to the original service e but additionál abhavior - such a s logging - before or afteur the method execution.
A program végrehajtásaing Logging with the Decorator Mintan
Suppose youhave a service interface:
public interface DataService {
void fetchData();
}
You can creete a concrete implementation:
public class RealDataService implements DataService {
@Override
public void fetchData() {
// Fetch data from a database or external API
}
}
Next, create a adentator 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.");
}
}
Usingthe Decorator
To add logging, instantiate the adentator with yur extening service:
DataService service = new RealDataService();
DataService loggedService = new LoggingDataServiceDecorator(service);
// Now, calling fetchData will include logging
loggedService.fetchData();
Előnyök o f te Decorator Minta n
- A létezési funkciók javítása az eredeti modifying-dal
- Promotes code reuse and separation of concerns
- Előnyök adding multiplace layers of behavior dinamically
Usinggthe adentiatur applications easier to extended d maintain.