This pattern is using for memory optimization. For example, we have business application, where are registered 100 000 users, but some of them have same first names or surnames. In this case we should create unique values of variables and create link for them. Therefore we can optimize memory using.
Let’s see example. We created user list, part of list users have similar first or last names. We used dictionary list, that have only 4 values: Michael; Brown; Williams; David. And when we want to get user names, public property receive information from nameIndexArray, consolidate it with vocabList and then give information as string.
internal class Program
{
static void Main(string[] args)
{
List<User> users = new List<User>();
users.Add(new User("Michael Brown"));
users.Add(new User("Michael Williams"));
users.Add(new User("David Brown"));
users.Add(new User("David Williams"));
foreach (User user in users)
Console.WriteLine(user.Name);
Console.WriteLine();
Console.WriteLine("DiagInfo: "+User.GetVocabList());
Console.ReadLine();
}
}
public class User
{
static List<string> vocabList = new List<string>();
private int[] nameIndexArray;
public User(string Name)
{
int addOrGet(string word)
{
int indexOfWord = vocabList.IndexOf(word);
if (vocabList.IndexOf(word) < 0)
{
vocabList.Add(word);
return vocabList.Count() - 1;
}
return indexOfWord;
}
nameIndexArray = Name.Split(' ').Select(addOrGet).ToArray();
}
public static string GetVocabList()
{
return String.Join("; ", vocabList);
}
public string Name => string.Join(" ", nameIndexArray.Select(i => vocabList[i]));
}