开发者

Is there a better way to model the feeding behavior of an organism?

Basically each entity would have a collection of feeding behaviors that it would follow. For some reason the model I came up with does not feel right. I think the most troubling part is that using singletons made sense.

Is there a better way?

public bool IsEntityEdible(Entity target)
{
    foreach (var feedingBehavior in FeedingBehaviors)
    {
        if (feedingBehavior.WouldEat(target))
        {
            return true;
        }
    }

    return false;
}

public abstract class FeedingBehavior
{
    public abstract bool WouldEat(Entity entity);   
}

public sealed class Myrmecophagy : FeedingBehavior
{
    public readonly static Myrmecophagy Instance = new Myrmecophagy(开发者_运维技巧);

    private Myrmecophagy() { }

    public override bool WouldEat(Entity entity)
    {
        return entity is Ant || entity is Termite;
    }
}


I think your solution is perfectly fine. An organism is composed of feeding behaviours where each feeding behaviour is an immutable object that implements the behaviour. Since behaviour is usually implemented as classes, your singletons look like perfectly valid use here.

The only thing I can think of is that the publicly visible class for the Myrmecophagy behaviour might be unnecessary. You could simply place the class inside FeedingBehavior, make it private and only expose a public static read-only field holding the singleton.

In case you're interested, I've got an implementation of RFC3454 in one of my projects. The RFC describes a framework for preparing strings according to different profiles. So I created an abstract class StringPreparer which exposes several standard profiles as singleton instances or which alternatively can be extended by users to implement custom profiles:

public abstract class StringPreparer
{
   public static readonly StringPreparer Domain = new DomainStringPreparer();
   public static readonly StringPreparer Node = new NodeStringPreparer();
   public static readonly StringPreparer Resource = new ResourceStringPreparer();
   public static readonly StringPreparer Sasl = new SaslStringPreparer();
   public static readonly StringPreparer Trace = new TraceStringPreparer();

   protected StringPreparer()
   {
   }

   public abstract bool TryPrepare(
      string text, int offset, int count, out string result);

   ...

   private class DomainStringPreparer : StringPreparer
   {
      public override bool TryPrepare(
         string text, int offset, int count, out string result)
      {
         ...
      }
   }

   private class NodeStringPreparer : StringPreparer
   {
      ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜