Untitled
unknown
plain_text
2 years ago
3.6 kB
4
Indexable
Certainly! I can suggest a design pattern that can be used to improve the clean code in the provided program. One of the commonly used design patterns is the Singleton pattern, which ensures that only one instance of a class can be created. In the given program, the PlayerDataStorage class could benefit from using the Singleton pattern. Currently, each instance of the PlayerDataStorage class operates on the same file, but each instance opens and closes the file individually, which could be inefficient. To implement the Singleton pattern, you can modify the PlayerDataStorage class as follows: class PlayerDataStorage : IPlayerDataStorage { private static PlayerDataStorage instance; private static readonly object lockObject = new object(); private readonly string filePath; private PlayerDataStorage(string path) { filePath = path; } public static PlayerDataStorage Instance { get { lock (lockObject) { if (instance == null) { instance = new PlayerDataStorage("result.txt"); } return instance; } } } public void Write(string name, int guesses) { lock (lockObject) { using (StreamWriter output = new StreamWriter(filePath, append: true)) { output.WriteLine(name + "#&#" + guesses); } } } public void ShowTopList() { lock (lockObject) { using (StreamReader input = new StreamReader(filePath)) { List<IPlayerData> results = new List<IPlayerData>(); string line; while ((line = input.ReadLine()) != null) { string[] nameAndScore = line.Split(new string[] { "#&#" }, StringSplitOptions.None); string name = nameAndScore[0]; int guesses = Convert.ToInt32(nameAndScore[1]); IPlayerData pd = new PlayerData(name, guesses); int pos = results.IndexOf(pd); if (pos < 0) { results.Add(pd); } else { results[pos].Update(guesses); } } results.Sort((p1, p2) => p1.Average().CompareTo(p2.Average())); Console.WriteLine("Player Games Average"); foreach (IPlayerData p in results) { Console.WriteLine(string.Format("{0,-9}{1,5:D}{2,9:F2}", p.Name, p.NGames, p.Average())); } } } } } In the modified code, the PlayerDataStorage class now has a private constructor, a private static instance field, and a public static Instance property that provides access to the singleton instance. The instance is lazily initialized, and a lock is used to ensure thread safety. Now, instead of creating an instance of PlayerDataStorage using new PlayerDataStorage(resultFilePath), you can access the singleton instance by calling PlayerDataStorage.Instance. For example: IPlayerDataStorage storage = PlayerDataStorage.Instance; By using the Singleton pattern, you ensure that all parts of the program access the same instance of PlayerDataStorage and avoid unnecessary file opening and closing operations.
Editor is loading...