设计模式实战:日志系统的设计与实现

时间:2024-10-01 18:33:46
// 统一的日志格式接口 interface LogFormatAdapter { String format(String message); } // 适配器实现 class JsonLogFormatAdapter implements LogFormatAdapter { private JsonLogFormat jsonLogFormat; public JsonLogFormatAdapter(JsonLogFormat jsonLogFormat) { this.jsonLogFormat = jsonLogFormat; } @Override public String format(String message) { return jsonLogFormat.toJson(message); } } class XmlLogFormatAdapter implements LogFormatAdapter { private XmlLogFormat xmlLogFormat; public XmlLogFormatAdapter(XmlLogFormat xmlLogFormat) { this.xmlLogFormat = xmlLogFormat; } @Override public String format(String message) { return xmlLogFormat.toXml(message); } } // 现有的日志格式类 class JsonLogFormat { public String toJson(String message) { return "{ \"log\": \"" + message + "\" }"; } } class XmlLogFormat { public String toXml(String message) { return "<log>" + message + "</log>"; } }