有人能给出同时使用组合模式和责任链模式的实际示例吗?
谢谢
这个例子结合了 责任链模式、命令模式和组合模式,并利用在 .NET 中熟悉的 Try*
方法风格。
给定 命令 和 处理器 类型:
public interface IResults { }
public interface ICommand { }
public interface IHandler
{
Boolean TryHandle(ICommand command, out IResults results);
}
给定一些 IHandler
的实现:
public class FooHandler : IHandler
{
public Boolean TryHandle(ICommand command, out IResults results)
{
// ...
}
}
public class BarHandler : IHandler
{
public Boolean TryHandle(ICommand command, out IResults results)
{
// ...
}
}
以下是一个复合IHandler实现的示例:
public class CompositeHandler : IHandler
{
public IList<IHandler> Handlers { get; } = new List<IHandler>();
public Boolean TryHandle(ICommand command, out IResults results)
{
foreach (var handler in this.Handlers) {
if (handler.TryHandle(command, out results)) {
return true;
}
}
results = null;
return false;
}
}
在客户端代码中使用:
var command = /* ... */;
var handler = new CompositeHandler();
handler.Handlers.Add(new FooHandler());
handler.Handlers.Add(new BarHandler());
IResults results;
if (handler.TryHandle(command, out results)) {
// handled
}
else {
// not handled
}
通过使用泛型,类型参数化/约束也可以确保一定程度的安全性:
public interface IResults { }
public interface ICommand<TResults>
where TResults : IResults
{
// ...
}
public interface IHandler<TCommand, TResults>
where TCommand : ICommand<TResults>
where TResults : IResults
{
// ...
}
实际上,可能无法给出一个确定的答案,但我可以看出你需要一系列责任链来完成任务。以下是一个Python示例:
>>> class DevelopmentPerformanceMonitor():
... def getPerformanceMonitorHandlers():
... return []
...
>>> class ProductionPerformanceMonitor():
... def getPerformanceMonitorHandlers():
... return [check_cpu_under_load, check_available_hd]
...
>>> class DevelopmentExceptionMonitor():
... def getExceptionHandlers():
... return [email_local_root, log_exception]
...
>>> class ProductionExceptionMonitor():
... def getExceptionHandlers():
... return [emails_system_admin, log_exception, create_ticket]
...
>>> class SomeSystem:
... pm = None # Performance Monitor
... em = None # Exception Monitor
... def __init__(self, performance_monitor, exception_monitor):
... pm = performance_monitor
... em = exception_monitor
... def on_exception(e):
... for handler in em.getExceptionHandlers():
... handler(e)
... def perform_performance_monitoring(s):
... for handler in pm.getPerformanceMonitorHandlers():
... handler(s)