[英]Is this bad design?
我有一个控件,它提供了选择机制。 但是,它选择的项目不适合一般消费,而是必须投影到按日期参数化的其他类型中。
除此之外,还有一些控件希望封装相同的信息,更重要的是,即使原始控件的选择已更改,也希望保留特定的选择。 因此,仅链接方法不起作用,因为原始控件的方法将始终返回其当前选择的投影。
要解决此问题,我创建了一个返回闭包的属性,该闭包根据特定选择执行投影。 这样,我可以封装投影并保护所投影的实型,还可以封装特定的集合。 这是我所拥有的简化版本。
public class MySelectionControl
{
public Func<DateTime, IEnumerable<MyProjectedType>> CreateSelectionForDate
{
get
{
// Take a copy of the selection before creating the lambda so
// that the source items won't change if the selection does.
IEnumerable<MyRealType> copyOfSelection = this.realSelection.ToList();
return weekEnding =>
copyOfSelection.Select(x => new MyProjectedType(x, weekEnding));
}
}
}
然后可以像以下方法一样调用它:
MySelectionControl control = new MySelectionControl();
// Gives the current selection for a given date.
control.CreateSelectionForDate(DateTime.Today);
// Takes a copy of the selection for later use, regardless of
// whether the original selection changes.
var selectedItemsProjection = control.CreateSelectionForDate;
那么,这是糟糕的设计还是巧妙地使用了代表?
由于这种安排的目的是提供一个上下文和从该上下文中运行的方法,因此最好像这样使用它:
Closure closure = selectionControl.GetClosure(DateTime.Today);
closure.DateSelection ...
我认为这非常聪明。 我唯一要做的就是将您的属性( CreateSelectionForDate
)转换为方法(无论如何对我来说)将使代码更清晰。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.