The factory pattern

The next pattern applied by the team is the GoF factory pattern. The pattern introduces a creator whose responsibility is the instantiation of implementations of a specific type. Its purpose is to encapsulate the complexity around constructing types. The factory pattern allows for more flexibility as the application changes, by limiting the amount of required change compared to whether the construction was in the calling class. This is because the complexity of the construction is in one location, instead of distributed in multiple locations across the application.

In the FlixOne example, InventoryCommandFactory implements the pattern and shields the details of constructing each of the different InventoryCommand instances. In this scenario, the input received from the console application will be used to determine the concrete implementation of InventoryCommand to return. It is important to note that the return type is the InventoryCommand abstract class, thus shielding the calling class from the details of the concrete class.

InventoryCommandFactory is shown in the following code block. But, for now, focus on the GetCommand method as this implements the factory pattern:

public class InventoryCommandFactory : IInventoryCommandFactory
{
private readonly IUserInterface _userInterface;
private readonly IInventoryContext _context = InventoryContext.Instance;

public InventoryCommandFactory(IUserInterface userInterface)
{
_userInterface = userInterface;
}

...
}

GetCommand uses a given string to determine the specific implementation of InventoryCommand to return:

public InventoryCommand GetCommand(string input)
{
switch (input)
{
case "q":
case "quit":
return new QuitCommand(_userInterface);
case "a":
case "addinventory":
return new AddInventoryCommand(_userInterface, _context);
case "g":
case "getinventory":
return new GetInventoryCommand(_userInterface, _context);
case "u":
case "updatequantity":
return new UpdateQuantityCommand(_userInterface, _context);
case "?":
return new HelpCommand(_userInterface);
default:
return new UnknownCommand(_userInterface);
}
}

All commands require IUserInterface to be supplied, but some also require access to the repository. These will be supplied with the singleton instance of IInventoryContext.

The factory pattern is often used with an Interface as the return type. It is illustrated here as the InventoryCommand base class.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.38.117