
Untitled
By: a guest on
Jun 17th, 2012 | syntax:
None | size: 2.46 KB | hits: 16 | expires: Never
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Patterns
{
/// <summary>
/// Represents a pattern node
/// </summary>
class PatternNode
{
private Dictionary<Dimension, ItemType> _terminators = new Dictionary<Dimension, ItemType>(DimensionEqualityComparer.Default);
// You may want to flip this to a dictionary instead - depending on how many items you have.
private PatternNode[] _nodes;
private static readonly int _nodesCount;
static PatternNode()
{
var max = 0;
foreach (int val in Enum.GetValues(typeof(ItemType)))
{
max = Math.Max(max, val);
}
_nodesCount = max + 1;
}
/// <summary>
/// Gets the <see cref="Patterns.PatternNode"/> with the specified item type.
/// </summary>
public PatternNode this[ItemType next]
{
get
{
if (_nodes == null)
return null;
return _nodes[(int)next];
}
}
/// <summary>
/// Gets or sets the <see cref="Patterns.ItemType"/> with the specified dimension.
/// </summary>
public ItemType this[Dimension dimension]
{
get
{
ItemType result;
if (!_terminators.TryGetValue(dimension, out result))
return ItemType.Nothing;
return result;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="PatternNode"/> class.
/// </summary>
public PatternNode()
{
}
/// <summary>
/// Adds the specified terminator.
/// </summary>
/// <param name="dimension">The dimension.</param>
/// <param name="next">Type of the item.</param>
public void Add(Dimension dimension, ItemType itemType)
{
_terminators.Add(dimension, itemType);
}
/// <summary>
/// Creates or gets a node for the specified item type.
/// </summary>
/// <param name="next">The next item type.</param>
public PatternNode Add(ItemType next)
{
// Definitely not thread safe.
var nodes = _nodes ?? (_nodes = new PatternNode[_nodesCount]);
return _nodes[(int)next] ?? (_nodes[(int)next] = new PatternNode());
}
}
}