Skip to content

Instantly share code, notes, and snippets.

@yusufcakal
Last active January 22, 2020 12:05
Show Gist options
  • Save yusufcakal/89cd3ee10fb767d91a406c6ed4a3630e to your computer and use it in GitHub Desktop.
Save yusufcakal/89cd3ee10fb767d91a406c6ed4a3630e to your computer and use it in GitHub Desktop.
Application Decorator Pattern in Java
public interface BaseService<T extends BaseRequest, R extends BaseResponse> {
R execute(T request);
}
public class ServiceLogDecorator<T extends BaseRequest, R extends BaseResponse> implements BaseService<T, R> {
private Logger logger;
private BaseService<T, R> service;
public static <T extends BaseRequest, R extends BaseResponse> ServiceLogDecorator<T, R> decorate(BaseService<T, R> service) {
return new ServiceLogDecorator<>(service);
}
private ServiceLogDecorator(BaseService<T, R> service) {
this.service = service;
logger = LoggerFactory.getLogger(service.getClass());
}
@Override
public R execute(T request) {
putLog(request);
R response = service.execute(request);
putLog(response);
return response;
}
private void putLog(Object object) {
try {
logger.info(String.valueOf(object));
} catch (Exception ex) {
logger.error("An error occurred while logging " + object.getClass().getSimpleName(), ex);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment