Frage

Ich versuche, eine einfache Implementierung der Spezifikation Musters in meiner Domain-Schicht zu tun.

Wenn ich eine statische Klasse volle Spezifikationen wie folgt:

public static class FooSpecifications
{
  public static Func<Foo, bool> IsSuperhuman
  {
    get
    {
      return foo => foo.CanShootLasersOutOfItsEyes && foo.CanFly;
    }
  }
}

Dann kann ich so wunderbare Dinge tun:

IEnumerable<Foo> foos = GetAllMyFoos();
var superFoos = foos.Where(FooSpecifications.IsSuperhuman);

Ich kann auch Bool Methode Foo hinzufügen, um zu bestimmen, ob eine bestimmte Instanz eine Spezifikation erfüllt:

public bool Meets(Func<Foo, bool> specification)
{
  return specification.Invoke(this);
}

Da Foo, wie alle meiner Domain Entitäten erweitert Domainobject, gibt es eine Weise, die ich eine generische Implementierung setzen kann von Meets () in die Domainobject mir zu retten Umsetzung Erfüllt () separat in jedem Unternehmen?

War es hilfreich?

Lösung

So etwas wie dieses ...

    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

Bearbeiten

Vielleicht wird es besser sein Treffen Methode zur Erweiterung zu übersetzen. Dies muss in Typ-Parameter entfernen.

    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
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top