顾名思义,责任链模式(Chain of Responsibility Pattern)为请求创建了一个接收者对象的链。这种模式给予请求的类型,对请求的发送者和接收者进行解耦。这种类型的设计模式属于行为型模式。
在这种模式中,通常每个接收者都包含对另一个接收者的引用。如果一个对象不能处理该请求,那么它会把相同的请求传给下一个接收者,依此类推。
python实现
from abc import ABCMeta, abstractmethod
class Handler(metaclass=ABCMeta):
@abstractmethod
def handle_leave(self):
pass
class GeneralManager(Handler):
def handle_leave(self,day):
if day<15:
print("总经理批准请假")
else:
print("请假太多了,你离职吧")
class DepartmentManager(Handler):
def __init__(self):
self.next = GeneralManager()
def handle_leave(self,day):
if day <=5:
print("部门经理批注请假")
else:
print("部门经理权限不足")
self.next.handle_leave(day)
class ProjectManager(Handler):
def __init__(self):
self.next = DepartmentManager()
def handle_leave(self,day):
if day<=3:
print("项目经理批准")
else:
print("项目经理权限不足")
self.next.handle_leave(day)
day = 17
obj = ProjectManager()
obj.handle_leave(day)
结果 E:\source\python\code2pdfword\venv\Scripts\python.exe E:/source/python/code2pdfword/designpattern/dp/chainOfResponsibility.py 项目经理权限不足 部门经理权限不足 请假太多了,你离职吧
dart 实现
避免请求发送者与接收者耦合在一起,让多个对象都有可能接收请求,将这些对象连接成一条链,并且沿着这条链传递请求,直到有对象处理它为止。
主要解决:职责链上的处理者负责处理请求,客户只需要将请求发送到职责链上即可,无须关心请求的处理细节和请求的传递,所以职责链将请求的发送者和请求的处理者解耦了。
何时使用:在处理消息的时候以过滤很多道。
如何解决:拦截的类都实现统一接口
abstract class AbstractLogger {
static int INFO = 1;
static int DEBUG = 2;
static int ERROR = 3;
late int _level;
AbstractLogger? _nextLogger;
void setNextLogger(AbstractLogger nextLogger) {
this._nextLogger = nextLogger;
}
void logMessage(int level, String msg) {
if (this._level <= level) {
write(msg);
}
if (_nextLogger != null) {
_nextLogger?.logMessage(level, msg);
}
}
void write(String msg) {
print("writeinnggggggg ");
}
}
class ConsoleLogger extends AbstractLogger {
ConsoleLogger(int level) {
this._level = level;
}
@override
void write(String msg) {
// TODO: implement write
print("standard console:logger $msg");
}
}
class ErrorLogger extends AbstractLogger {
ErrorLogger(int level) {
this._level = level;
}
@override
void write(String msg) {
// TODO: implement write
print("error console :logger $msg");
}
}
class FileLogger extends AbstractLogger {
FileLogger(int level) {
this._level = level;
}
@override
void write(String msg) {
// TODO: implement write
print("File:logger $msg");
}
}
class LoggerFactory {
static AbstractLogger getChainOfLogger() {
AbstractLogger errorLogger = ErrorLogger(AbstractLogger.ERROR);
AbstractLogger fileLogger = FileLogger(AbstractLogger.DEBUG);
AbstractLogger consoleLogger = ConsoleLogger(AbstractLogger.INFO);
errorLogger.setNextLogger(fileLogger);
fileLogger.setNextLogger(consoleLogger);
return errorLogger;
}
}
void main(List<String> args) {
AbstractLogger loggerChain = LoggerFactory.getChainOfLogger();
loggerChain.logMessage(AbstractLogger.INFO, "info xxxxx");
// // loggerChain.logMessage(AbstractLogger.DEBUG, "debug xxxxx");
// loggerChain.logMessage(AbstractLogger.ERROR, "this is an error");
}