责任链模式 为请求创建了一个接收者对象的链。这种模式给予请求的类型,对请求的发送者和接收者进行解耦。这种类型的设计模式属于行为型模式。在这种模式中,通常每个接收者都包含对另一个接收者的引用。如果一个对象不能处理该请求,那么它会把相同的请求传给下一个接收者,依此类推。
总结:最高等级的,可以调用 下属的 所有 子。
优点: 1、降低耦合度。它将请求的发送者和接收者解耦。 2、简化了对象。使得对象不需要知道链的结构。 3、增强给对象指派职责的灵活性。通过改变链内的成员或者调动它们的次序,允许动态地新增或者删除责任。 4、增加新的请求处理类很方便。
下面通过 示例 展示 责任链模式:
namespace 责任链模式
{
internal class Program
{
static void Main(string[] args)
{
AbstractLogger fileLogger = new FileLogger(AbstractLogger.Info);
AbstractLogger consoleLogger = new ConsoleLogger(AbstractLogger.Debug);
fileLogger.SetNextChain(consoleLogger);
//最高等级的,可以调用 下属的 所有 子
fileLogger.LogMessage(AbstractLogger.Info, "info信息");
fileLogger.LogMessage(AbstractLogger.Debug, "Debug信息");
/*
* 控制台:
* 文件写成 日志为:info信息
文件写成 日志为:Debug信息
控制台日志为:Debug信息
*/
}
}
//创建抽象的记录器类
public abstract class AbstractLogger
{
public static int Info = 1;
public static int Debug = 2;
public static int Error =3;
protected int level;
protected AbstractLogger nextChain;
public void SetNextChain(AbstractLogger abstractLogger)
{
nextChain = abstractLogger;
}
public void LogMessage(int level,string msg)
{
if (this.level <= level)
{
Write(msg);
}
if(nextChain != null)
{
nextChain.LogMessage(level, msg);
}
}
public abstract void Write(string msg);
}
public class FileLogger : AbstractLogger
{
public FileLogger(int level)
{
base.level = level;
}
public override void Write(string msg)
{
Console.WriteLine("文件写成 日志为:"+msg);
}
}
public class ConsoleLogger : AbstractLogger
{
public ConsoleLogger(int level)
{
base.level = level;
}
public override void Write(string msg)
{
Console.WriteLine("控制台日志为:" + msg);
}
}
}
缺点: 1、不能保证请求一定被接收。 2、系统性能将受到一定影响,而且在进行代码调试时不太方便,可能会造成循环调用。 3、可能不容易观察运行时的特征,有碍于除错。