我正在尝试在我的域层中执行规范模式的简单实现。
如果我有一个充满这样规格的静态类:
public static class FooSpecifications
{
public static Func<Foo, bool> IsSuperhuman
{
get
{
return foo => foo.CanShootLasersOutOfItsEyes && foo.CanFly;
}
}
}
然后我可以做这样的奇妙事情:
IEnumerable<Foo> foos = GetAllMyFoos();
var superFoos = foos.Where(FooSpecifications.IsSuperhuman);
我还可以向Foo添加bool方法,以确定特定实例是否符合规范:
public bool Meets(Func<Foo, bool> specification)
{
return specification.Invoke(this);
}
鉴于Foo和我的所有域实体一样,扩展了DomainObject,有没有办法将Meets()的泛型实现放到DomainObject中以节省我在每个实体中单独实现Meets()?
答案 0 :(得分:0)
像这样......
public abstract class DomainObj<T> // T - derived type
where T : DomainObj<T>
{
public bool Meets(Func<T, bool> specification)
{
return specification.Invoke((T) this);
}
}
public class Foo : DomainObj<Foo> {}
public class Bar : DomainObj<Bar> {}
Func<Foo, bool> foospec = x => true;
Func<Bar, bool> barspec = x => true;
var foo = new Foo();
var bar = new Bar();
foo.Meets(foospec);
foo.Meets(barspec); // won't compile because of mismatched types of spec and object instance
修改强>
将Meet方法转换为扩展名可能会更好。这将删除类型参数中的需要。
public abstract class DomainObj
{
}
public static class DomainObjExtensions
{
public static bool Meets<T>(this T obj, Func<T, bool> f)
where T : DomainObj
{
return f(obj);
}
}
public class Foo : DomainObj {}
public class Bar : DomainObj {}
Func<Foo, bool> foospec = x => true;
Func<Bar, bool> barspec = x => true;
var foo = new Foo();
var bar = new Bar();
foo.Meets(foospec);
foo.Meets(barspec); // error