我使用受 thekip 建议启发的中间“工厂”解决了该问题,但未触及构造函数中需要谓词和函数的对象(上例中的 MyClass)。此解决方案将在 Spring 中处理代表的“问题”保留在 MyClass 的实现之外(与 thekip 的建议相反,但感谢您的回答)。
这是我配置这种情况的方法(在 Spring.Net 中设置委托,使用基于对象的工厂模式)。
MyDelegator 类是谓词/函数使用的示例实现
(此处的对象,但可以是其他任何适合谓词/函数参数的东西):
public class MyDelegator
{
// for the predicate Predicate<TInput> condition, implemented with object
public bool Condition(object input)
{
...
}
//for the Func<TInput, TOutput> result, implemented with object
public object Evaluate(object input)
{
...
}
}
... 那么你需要一个带有谓词和或函数的对象的容器(可以
也要分班)...
public class MySpringConfigurationDelegateObjectContainer
{
private readonly Predicate<object> condition;
private readonly Func<object, object> evaluate;
public MySpringConfigurationDelegateObjectContainer(MyDelegator strategy)
{
condition = strategy.Condition;
evaluate = strategy.Evaluate;
}
public Predicate<object> GetConditionMethod()
{
return condition;
}
public Func<object, object> GetEvaluateMethod()
{
return evaluate;
}
}
...这可以通过这种方式在 Spring.Net xml 中进行配置
<!-- a simple container class, just has the object with the method to call -->
<object id="Container" type="MySpringConfigurationDelegateObjectContainer">
<constructor-arg name="myDelegateObject">
<!-- put the object with the delegate/func/predicate here -->
<object type="MyDelegator" />
</constructor-arg>
</object>
现在您可以在配置中的任何位置使用它来处理带有谓词/函数的对象
(无需更改需要谓词/函数的类)
<object id="NeedAPredicateAndFuncInConstructor" type="...">
...
<constructor-arg name="condition">
<object factory-method="GetConditionMethod" factory-object="Container" />
</constructor-arg>
<constructor-arg name="result">
<object factory-method="GetEvaluateMethod" factory-object="Container" />
</constructor-arg>
...
</object>
就是这样。有什么建议可以改进这个解决方案吗?也许,Spring.net 已经有一个通用的解决方案......