Jypeli 10
The simple game programming library
Factory.cs
Siirry tämän tiedoston dokumentaatioon.
1using System;
2using System.Collections.Generic;
3
4namespace Jypeli
5{
6 public partial class Game
7 {
14 public void AddFactory<T>( string tag, Factory.FactoryMethod method )
15 {
16 Factory.AddFactory<T>( tag, method );
17 }
18
25 public void RemoveFactory<T>( string tag, Factory.FactoryMethod method )
26 {
27 Factory.RemoveFactory<T>( tag, method );
28 }
29
36 public T FactoryCreate<T>( string tag )
37 {
38 return Factory.FactoryCreate<T>( tag );
39 }
40 }
41
42 public static class Factory
43 {
45 {
46 public Type type;
47 public string tag;
48
49 public FactoryKey( Type type, string tag )
50 {
51 this.type = type;
52 this.tag = tag;
53 }
54 }
55
56 public delegate object FactoryMethod();
57 static Dictionary<FactoryKey, FactoryMethod> constructors = new Dictionary<FactoryKey, FactoryMethod>();
58
59 public static void AddFactory<T>( string tag, FactoryMethod method )
60 {
61 foreach ( var key in constructors.Keys.FindAll<FactoryKey>( k => k.type == typeof( T ) && k.tag == tag ) )
62 {
63 // Overwrite an existing method
64 constructors[key] = method;
65 return;
66 }
67
68 FactoryKey newKey = new FactoryKey( typeof( T ), tag );
69 constructors.Add( newKey, method );
70 }
71
72 public static void RemoveFactory<T>( string tag, FactoryMethod method )
73 {
74 foreach ( var key in constructors.Keys.FindAll<FactoryKey>( k => k.type == typeof( T ) && k.tag == tag ) )
75 constructors.Remove( key );
76 }
77
78 public static T FactoryCreate<T>( string tag )
79 {
80 return (T)FactoryCreate( typeof( T ), tag );
81 }
82
83 internal static object FactoryCreate( Type type, string tag )
84 {
85 foreach ( FactoryKey key in constructors.Keys )
86 {
87 if ( key.type == type && key.tag == tag )
88 return constructors[key].Invoke();
89 }
90
91 throw new KeyNotFoundException( "Key " + tag + " for class " + type.Name + " was not found." );
92 }
93 }
94}
static object FactoryCreate(Type type, string tag)
Definition: Factory.cs:83
static T FactoryCreate< T >(string tag)
Definition: Factory.cs:78
static Dictionary< FactoryKey, FactoryMethod > constructors
Definition: Factory.cs:57
static void AddFactory< T >(string tag, FactoryMethod method)
Definition: Factory.cs:59
delegate object FactoryMethod()
static void RemoveFactory< T >(string tag, FactoryMethod method)
Definition: Factory.cs:72
void RemoveFactory< T >(string tag, Factory.FactoryMethod method)
Poistaa tehdasmetodin.
Definition: Factory.cs:25
T FactoryCreate< T >(string tag)
Käyttää tehdasmetodia uuden olion luomiseen ja palauttaa olion.
Definition: Factory.cs:36
void AddFactory< T >(string tag, Factory.FactoryMethod method)
Luo tehdasmetodin tietylle tyypille ja tagille.
Definition: Factory.cs:14
FactoryKey(Type type, string tag)
Definition: Factory.cs:49