package com.company;
enum LogLevel {
DEBUG(0),
INFO(1),
WARN(2),
ERROR(3);
private final Integer enumCode;
private LogLevel(Integer enumCode) {
this.enumCode = enumCode;
}
private Integer getEnumCode() {
return enumCode;
}
}
abstract class LogProcessor {
protected LogProcessor nextLogProcessor;
public LogProcessor(LogProcessor nextLogProcessor) {
this.nextLogProcessor = nextLogProcessor;
}
public LogProcessor() {
this.nextLogProcessor = null;
}
public void log(LogLevel logLevel, String message) {
if (this.nextLogProcessor != null) {
this.nextLogProcessor.log(logLevel, message);
}
}
}
class InfoLogProcessor extends LogProcessor {
public InfoLogProcessor(LogProcessor nextLogProcessor) {
this.nextLogProcessor = nextLogProcessor;
}
public InfoLogProcessor() {
this.nextLogProcessor = null;
}
public void log(LogLevel logLevel, String message) {
if (LogLevel.INFO.equals(logLevel)) {
System.out.println("[" + LogLevel.INFO + "] " + message);
} else {
System.out.println("[" + LogLevel.INFO + "] This request can't be processed");
super.log(logLevel, message);
}
}
}
class WarnLogProcessor extends LogProcessor {
public WarnLogProcessor(LogProcessor nextLogProcessor) {
this.nextLogProcessor = nextLogProcessor;
}
public WarnLogProcessor() {
this.nextLogProcessor = null;
}
public void log(LogLevel logLevel, String message) {
if (LogLevel.WARN.equals(logLevel)) {
System.out.println("[" + LogLevel.WARN + "] " + message);
} else {
System.out.println("[" + LogLevel.WARN + "] This request can't be processed");
super.log(logLevel, message);
}
}
}
class ErrorLogProcessor extends LogProcessor {
public ErrorLogProcessor(LogProcessor nextLogProcessor) {
this.nextLogProcessor = nextLogProcessor;
}
public ErrorLogProcessor() {
this.nextLogProcessor = null;
}
public void log(LogLevel logLevel, String message) {
if (LogLevel.ERROR.equals(logLevel)) {
System.out.println("[" + LogLevel.ERROR + "] " + message);
} else {
System.out.println("[" + LogLevel.ERROR + "] This request can't be processed");
super.log(logLevel, message);
}
}
}
public class CombinedClass {
public static void main(String[] args) {
LogProcessor logProcessor = new InfoLogProcessor(new WarnLogProcessor(new ErrorLogProcessor()));
logProcessor.log(LogLevel.INFO, "This is an info message");
System.out.println();
logProcessor.log(LogLevel.WARN, "This is an warn message");
System.out.println();
logProcessor.log(LogLevel.ERROR, "This is an error message");
}
}
上面是我使用责任链设计模式实现记录器的代码:
类:运行程序(用于主代码)、LogProcessor 接口(及其使用责任链模式的实现)和日志级别枚举。
我已经查阅了很多资源,但仍然没有找到为什么不能在这里使用工厂方法/简单工厂设计模式的具体原因。大多数答案都含糊地说工厂是一种创造性的设计模式,因此不能在这里使用。我的问题是为什么?即使它是一个创作模式,它也可以在相对较短的时间内为我完成同样的工作。在最坏的情况下,这里的责任链复杂度为 O(n),而工厂可以在更短的时间 O(1) 内完成(如果通过映射维护)。有人可以帮我一个具体的答案吗?
您始终可以组合 2 种模式以获得更好的性能和设计,例如,您可以将 COR 与复合模式或工厂模式组合。在给定的示例(日志记录)中,当您通过 Map 实现工厂模式时,空间复杂度将为 0(N),并且与 Factory 相比,COR 提供了以下灵活性。