Untitled
unknown
plain_text
2 years ago
2.8 kB
7
Indexable
Certainly! To demonstrate the Factory Method pattern in the provided code, let's create a factory that encapsulates the creation of IGoalGenerator objects. Here's an example implementation: csharp Copy code interface IGoalGeneratorFactory { IGoalGenerator CreateGoalGenerator(); } class RandomGoalGeneratorFactory : IGoalGeneratorFactory { public IGoalGenerator CreateGoalGenerator() { return new GoalGenerator(); } } In the above code, we define the IGoalGeneratorFactory interface that declares a method CreateGoalGenerator() which returns an instance of IGoalGenerator. Then, we create a concrete implementation RandomGoalGeneratorFactory that implements the factory interface and provides the implementation for creating a GoalGenerator instance. Now, let's modify the MainClass to use the factory to create the IGoalGenerator object: csharp Copy code class MainClass : IGame { private readonly IGoalGeneratorFactory goalGeneratorFactory; private readonly IGuessChecker guessChecker; private readonly IPlayerDataStorage playerDataStorage; public MainClass(IGoalGeneratorFactory generatorFactory, IGuessChecker checker, IPlayerDataStorage storage) { goalGeneratorFactory = generatorFactory; guessChecker = checker; playerDataStorage = storage; } public void Play() { // ... while (playOn) { IGoalGenerator goalGenerator = goalGeneratorFactory.CreateGoalGenerator(); string goal = goalGenerator.Generate(); // ... bbcc = guessChecker.Check(goal, guess); // ... } // ... } } In the modified code, we replace the direct creation of GoalGenerator with the factory method CreateGoalGenerator() from the goalGeneratorFactory instance. This allows us to create different implementations of IGoalGenerator by simply changing the factory used. To execute the code with the Factory Method pattern, you can make the following changes in the Main method: csharp Copy code static void Main(string[] args) { string resultFilePath = "result.txt"; IGoalGeneratorFactory generatorFactory = new RandomGoalGeneratorFactory(); IGuessChecker checker = new GuessChecker(); IPlayerDataStorage storage = new PlayerDataStorage(resultFilePath); IGame game = new MainClass(generatorFactory, checker, storage); game.Play(); } Now, when you run the program, it will create a GoalGenerator instance using the factory, which adheres to the Factory Method pattern. You can easily switch to a different implementation of IGoalGenerator by providing a different factory implementation, such as CustomGoalGeneratorFactory, without modifying the MainClass or IGame implementation.
Editor is loading...