设计模式之装饰模式(七)

一、概念

对已经存在的类进行修饰,以扩展其功能。

二、实例讲解

1、项目中我们使用log4j打印日志,一般是这样:

private static final Logger logger = LoggerFactory.getLogger(UserService.class);
logger.error(msg);

现需要将其转换为json格式,可以采用装饰模式。
2、代码实现

public class DecoratorLogger implements Logger {

   public Logger logger;

   public DecoratorLogger(Logger logger) {

       this.logger = logger;
   }
    
   @Override
   public void error(String str) {}

   @Override
   public void info(String str) {}
       
   //省略其他默认实现
}
public class JsonLogger extends DecoratorLogger {
public JsonLogger(Logger logger) {
        
        super(logger);
    }
        
    @Override
    public void info(String msg) {

        JSONObject result = composeBasicJsonResult();
        result.put("MESSAGE", msg);
        logger.info(result.toString());
    }
    
    @Override
    public void error(String msg) {
        
        JSONObject result = composeBasicJsonResult();
        result.put("MESSAGE", msg);
        logger.error(result.toString());
    }
    
    public void error(Exception e) {

        JSONObject result = composeBasicJsonResult();
        result.put("EXCEPTION", e.getClass().getName());
        String exceptionStackTrace = ExceptionUtils.getStackTrace(e);    
        result.put("STACKTRACE", exceptionStackTrace);
        logger.error(result.toString());
    }
    
    public static class JsonLoggerFactory {
        
        @SuppressWarnings("rawtypes")
        public static JsonLogger getLogger(Class clazz) {

            Logger logger = LoggerFactory.getLogger(clazz);
            return new JsonLogger(logger);
        }
    }
    
    private JSONObject composeBasicJsonResult() {
        //拼装了一些运行时信息
    }
}
private static final Logger logger = JsonLoggerFactory.getLogger(Component.class);
    logger.error(string);

三、总结

装饰模式的核心在于装饰,并不影响被装饰本身的核心功能。

你可能感兴趣的:(设计模式之装饰模式(七))