Jypeli  5
The simple game programming library
Factory.cs
Siirry tämän tiedoston dokumentaatioon.
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 
6 namespace Jypeli
7 {
8  public static class Factory
9  {
10  struct FactoryKey
11  {
12  public Type type;
13  public string tag;
14 
15  public FactoryKey( Type type, string tag )
16  {
17  this.type = type;
18  this.tag = tag;
19  }
20  }
21 
22  public delegate object FactoryMethod();
23  static Dictionary<FactoryKey, FactoryMethod> constructors = new Dictionary<FactoryKey, FactoryMethod>();
24 
25  public static void AddFactory<T>( string tag, FactoryMethod method )
26  {
27  foreach ( var key in constructors.Keys.FindAll( k => k.type == typeof( T ) && k.tag == tag ) )
28  {
29  // Overwrite an existing method
30  constructors[key] = method;
31  return;
32  }
33 
34  FactoryKey newKey = new FactoryKey( typeof( T ), tag );
35  constructors.Add( newKey, method );
36  }
37 
38  public static void RemoveFactory<T>( string tag, FactoryMethod method )
39  {
40  foreach ( var key in constructors.Keys.FindAll( k => k.type == typeof( T ) && k.tag == tag ) )
41  constructors.Remove( key );
42  }
43 
44  public static T FactoryCreate<T>( string tag )
45  {
46  return (T)FactoryCreate( typeof( T ), tag );
47  }
48 
49  internal static object FactoryCreate( Type type, string tag )
50  {
51  foreach ( FactoryKey key in constructors.Keys )
52  {
53  if ( key.type == type && key.tag == tag )
54  return constructors[key].Invoke();
55  }
56 
57  throw new KeyNotFoundException( "Key " + tag + " for class " + type.Name + " was not found." );
58  }
59  }
60 }
static void RemoveFactory< T >(string tag, FactoryMethod method)
Definition: Factory.cs:38
delegate object FactoryMethod()
static void AddFactory< T >(string tag, FactoryMethod method)
Definition: Factory.cs:25
static T FactoryCreate< T >(string tag)
Definition: Factory.cs:44