1 public class AbstractFactoryPattern
2 {
3 // An interface for all Cars
4 private interface IModel
5 {
6 int Cost { get; }
7 string Name { get; }
8 }
9
10 //Individual car model
11 public class Benz : IModel
12 {
13 public int Cost
14 {
15 get { return 20000; }
16 }
17
18 public string Name
19 {
20 get { return "Merc"; }
21 }
22 }
23
24 //Individual car model
25 public class BMW : IModel
26 {
27 public int Cost
28 {
29 get { return 21000; }
30 }
31
32 public string Name
33 {
34 get { return "BMW"; }
35 }
36 }
37
38 // Interface Car
39 private interface ICar
40 {
41 string Name { get; }
42 string Cost { get; }
43 }
44
45 // All concrete Cars
46 class Car<T> : ICar where T : IModel, new()
47 {
48 private readonly T model;
49
50 public Car()
51 {
52 model = new T();
53 }
54
55 public string Name
56 {
57 get { return model.Name; }
58 }
59
60 public string Cost
61 {
62 get { return model.Cost.ToString(); }
63 }
64 }
65
66 //Factory that creates the car
67 private interface IFactory
68 {
69 ICar CreateCar();
70 }
71
72 // Concrete Factories
73 class CarFactory<T> : IFactory where T : IModel, new()
74 {
75 public ICar CreateCar()
76 {
77 return new Car<T>();
78 }
79 }
80
81 class Client<T> where T : IModel, new()
82 {
83 public void ClientMain()
84 {
85 IFactory factory = new CarFactory<T>();
86 var car = factory.CreateCar();
87
88 Console.WriteLine( "My car is " + car.Name + " and its cost is " + car.Cost );
89 }
90 }
91
92 private static void Main()
93 {
94 new Client<Benz>().ClientMain();
95 new Client<BMW>().ClientMain();
96
97 //Output: My car is Merc and its cost is 20000
98 // My car is BMW and its cost is 21000
99
100 Console.ReadLine();
101 }
102 }