blob: 87ae36011e6432b46850e5dd76020d7f4ad76965 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
using System.Collections.Generic;
using System;
public class Factory<TKey, TBase>
{
delegate T InstantiateMethod<T> ();
Dictionary<TKey, InstantiateMethod<TBase>> _Products = new Dictionary<TKey, InstantiateMethod<TBase>> ();
public void Register<T> (TKey key) where T : TBase, new()
{
_Products.Add (key, Constructor<T>);
}
public TBase Produce (TKey key)
{
return _Products [key] ();
}
static TBase Constructor<T> () where T : TBase, new()
{
return new T ();
}
}
class BaseClass
{
}
class ChildClass1 : BaseClass
{
}
class ChildClass2 : BaseClass
{
}
class TestClass
{
public static int Main ()
{
var factory = new Factory<byte, BaseClass> ();
factory.Register<ChildClass1> (1);
factory.Register<ChildClass2> (2);
if (factory.Produce (1).GetType () != typeof (ChildClass1))
return 1;
if (factory.Produce (2).GetType () != typeof (ChildClass2))
return 2;
return 0;
}
}
|