1 using System
.Collections
.Generic
;
4 public class Factory
<TKey
, TBase
>
6 delegate T InstantiateMethod
<T
> ();
8 Dictionary
<TKey
, InstantiateMethod
<TBase
>> _Products
= new Dictionary
<TKey
, InstantiateMethod
<TBase
>> ();
10 public void Register
<T
> (TKey key
) where T
: TBase
, new()
12 _Products
.Add (key
, Constructor
<T
>);
15 public TBase
Produce (TKey key
)
17 return _Products
[key
] ();
20 static TBase Constructor
<T
> () where T
: TBase
, new()
30 class ChildClass1
: BaseClass
34 class ChildClass2
: BaseClass
40 public static int Main ()
42 var factory
= new Factory
<byte, BaseClass
> ();
43 factory
.Register
<ChildClass1
> (1);
44 factory
.Register
<ChildClass2
> (2);
46 if (factory
.Produce (1).GetType () != typeof (ChildClass1
))
49 if (factory
.Produce (2).GetType () != typeof (ChildClass2
))