1 public class FlyweightPattern
2 {
3 //Flyweight interface
4 public interface IPersonFlyweight
5 {
6 string FirstName { get; set; }
7 string LastName { get; set; }
8 string Address { get; set; }
9 string Designation { get; set; }
10 void Display( float salary );
11 }
12
13 //Flyweight
14 public class Person : IPersonFlyweight
15 {
16 //Internal state
17 public string FirstName { get; set; }
18 public string LastName { get; set; }
19 public string Address { get; set; }
20 public string Designation { get; set; }
21
22 public void Display( float salary )
23 {
24 Console.WriteLine( "Name : " + this.FirstName + ", Designation : " +
25 this.Designation + ", Salary : " + salary );
26 }
27
28 public override string ToString()
29 {
30 return FirstName;
31 }
32
33 }
34
35 public class Tester : Person
36 {
37 public Tester()
38 {
39 this.FirstName = "Tester";
40 this.LastName = "Tester";
41 this.Address = "Tester_Address";
42 this.Designation = "Tester";
43 }
44 }
45
46 public class Developer : Person
47 {
48 public Developer()
49 {
50 this.FirstName = "Developer";
51 this.LastName = "Developer";
52 this.Address = "Developer_Address";
53 this.Designation = "Developer";
54 }
55 }
56
57 public class FlyweightFactory
58 {
59 // Indexed list of IFlyweight objects
60 Dictionary<string, IPersonFlyweight> _flyweights =
61 new Dictionary<string, IPersonFlyweight>();
62
63 public FlyweightFactory()
64 {
65 _flyweights.Clear();
66 }
67
68 public Person this[string index]
69 {
70 get
71 {
72 if ( !_flyweights.ContainsKey( index ) )
73 {
74 _flyweights[index] = new Person();
75 }
76 return _flyweights[index] as Person;
77 }
78 }
79 }
80
81 private static void Main()
82 {
83 //List of person objects containing a Tester and a Developer object
84 Person[] personList = new Person[]
85 {
86 new Tester(), new Developer()
87 };
88
89 //shared state
90 FlyweightFactory people = new FlyweightFactory();
91
92 //external state
93 float salary = 50000;
94
95 foreach ( var person in personList )
96 {
97 if ( person is Tester )
98 {
99 Person p = people[person.ToString()];
100 person.Display( salary );
101 //Output : Name : Tester, Designation : Tester, Salary : 50000
102 }
103 else
104 {
105 Person p = people[person.ToString()];
106 person.Display( salary + 5000 );
107 //Output : Name : Developer, Designation : Developer, Salary : 55000
108 }
109 }
110
111 Console.ReadLine();
112 }
113 }