Design Pattern 2

2. Creational Pattern: Factory Method

Play this article

In the world of software design, object creation is a fundamental operation. However, the way you create these objects can significantly impact your application's flexibility, maintainability, and scalability. This is where design patterns come into play, providing tried-and-tested solutions to common design problems. One such pattern, the Factory Method, focuses on object creation and encapsulates it in a flexible and reusable manner. In this article, we will explore the Factory Method creational pattern in C#, understand its principles, and discover its real-world applications.

What is the Factory Method?

The Factory Method is a creational design pattern that defines an interface for creating an object but lets subclasses alter the type of objects that will be created. In essence, it provides an abstract framework for object creation while allowing concrete classes to determine the actual objects to instantiate. This separation of responsibilities promotes code reusability and maintainability.

Benefits of Using the Factory Method in C#

The Factory Method pattern offers several advantages in C#:

  1. Flexibility: It allows you to add new types of objects (ConcreteProducts) without modifying existing code. You can create new ConcreteCreators for each new type, adhering to the open-closed principle.

  2. Decoupling: The Creator and ConcreteCreator classes are decoupled from the ConcreteProduct classes. This separation promotes a high level of abstraction and reduces code dependencies.

  3. Reusability: You can reuse the Creator and ConcreteCreator classes across different parts of your application, as long as they adhere to the same interface.

  4. Maintenance: Changes to the product creation process are localized within the ConcreteCreators, making maintenance and updates more manageable.

Real-World Applications in C#

The Factory Method pattern is widely used in various software domains when coding in C#:

  1. GUI Libraries: Many graphical user interface libraries use the Factory Method to create different types of UI elements like buttons, windows, and dialog boxes.

  2. Logging Frameworks: Logging frameworks employ the Factory Method to create and configure different loggers and appenders.

  3. Game Development: In game development, Factory Methods can be used to create different types of game objects, such as characters, weapons, or enemies.

  4. Database Access: Database libraries often use Factory Methods to create database connections, allowing developers to work with various database systems seamlessly.

Creating GUI Elements Using Factory Methods

Let's implement the Factory Method pattern to create GUI elements in ASP.NET Core .NET 6. We will focus on creating buttons, text boxes, checkboxes, and dropdown lists.

GUI Element Interfaces

First, define interfaces for the GUI elements you want to create:

// IButton interface
public interface IButton
{
    string Render();
}

// ITextBox interface
public interface ITextBox
{
    string Render();
}

// ICheckBox interface
public interface ICheckBox
{
    string Render();
}

// IDropDownList interface
public interface IDropDownList
{
    string Render();
}

Concrete GUI Elements

Next, create concrete classes that implement these interfaces:

// Concrete Button class
public class Button : IButton
{
    public string Render()
    {
        return "<button>Submit</button>";
    }
}

// Concrete TextBox class
public class TextBox : ITextBox
{
    public string Render()
    {
        return "<input type='text' />";
    }
}

// Concrete CheckBox class
public class CheckBox : ICheckBox
{
    public string Render()
    {
        return "<input type='checkbox' />";
    }
}

// Concrete DropDownList class
public class DropDownList : IDropDownList
{
    public string Render()
    {
        return "<select><option>Option 1</option><option>Option 2</option></select>";
    }
}

Factory Interfaces and Concrete Factories

Now, define factory interfaces for creating these GUI elements:

// IGUIFactory interface
public interface IGUIFactory
{
    IButton CreateButton();
    ITextBox CreateTextBox();
    ICheckBox CreateCheckBox();
    IDropDownList CreateDropDownList();
}

Create concrete factories that implement these factory interfaces:

// WebGUIFactory class
public class WebGUIFactory : IGUIFactory
{
    public IButton CreateButton()
    {
        return new Button();
    }

    public ITextBox CreateTextBox()
    {
        return new TextBox();
    }

    public ICheckBox CreateCheckBox()
    {
        return new CheckBox();
    }

    public IDropDownList CreateDropDownList()
    {
        return new DropDownList();
    }
}

ASP.NET Core Controller

In your ASP.NET Core controller, use the Factory Method pattern to create and render GUI elements:

public class GUIController : Controller
{
    private readonly IGUIFactory _guiFactory;

    public GUIController(IGUIFactory guiFactory)
    {
        _guiFactory = guiFactory;
    }

    public IActionResult Index()
    {
        var button = _guiFactory.CreateButton();
        var textBox = _guiFactory.CreateTextBox();
        var checkBox = _guiFactory.CreateCheckBox();
        var dropDownList = _guiFactory.CreateDropDownList();

        var viewModel = new GUIViewModel
        {
            ButtonHtml = button.Render(),
            TextBoxHtml = textBox.Render(),
            CheckBoxHtml = checkBox.Render(),
            DropDownListHtml = dropDownList.Render()
        };

        return View(viewModel);
    }
}

ASP.NET Core View

Finally, create a view to display the rendered GUI elements:

@model GUIViewModel

<!DOCTYPE html>
<html>
<head>
    <title>GUI Elements</title>
</head>
<body>
    <div>
        @Html.Raw(Model.ButtonHtml)
    </div>
    <div>
        @Html.Raw(Model.TextBoxHtml)
    </div>
    <div>
        @Html.Raw(Model.CheckBoxHtml)
    </div>
    <div>
        @Html.Raw(Model.DropDownListHtml)
    </div>
</body>
</html>

ViewModel

Define a view model to hold the rendered HTML for GUI elements:

public class GUIViewModel
{
    public string ButtonHtml { get; set; }
    public string TextBoxHtml { get; set; }
    public string CheckBoxHtml { get; set; }
    public string DropDownListHtml { get; set; }
}
c

Conclusion

The Factory Method design pattern is a valuable tool in your software design arsenal when working with C#. It provides a clean and flexible way to create objects, ensuring that your code remains adaptable and maintainable as your application evolves. By understanding and implementing this pattern, you can streamline the object creation process and improve the overall structure of your C# software.

Did you find this article valuable?

Support Nestor Rojas by becoming a sponsor. Any amount is appreciated!