views:

65

answers:

1

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;
    }
}
+1  A: 

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
   {
      ...
dtb
Thanks, just getting confirmation that the basis of my idea is sound is extremely helpful. Your suggestion is icing on the cake.
ChaosPandion
I just noticed that this pattern can also be found in the .NET framework. Have a look at the System.Text.Encoding class which exposes several standard encodings (UTF8, UTF32, etc.) as singleton instances.
dtb