Design Patterns

Example 1: GUI Component Creation

Let's consider an application that needs to support different look-and-feel standards (Windows and macOS).

Step 1: Abstract Factory: Interface for creating GUI components.

public interface IGUIFactory
{
    IButton CreateButton();
    ICheckbox CreateCheckbox();
}

Step 2: Concrete Factory: Implementations for Windows and macOS.

public class WinFactory : IGUIFactory
{
    public IButton CreateButton() => new WinButton();
    public ICheckbox CreateCheckbox() => new WinCheckbox();
}

public class MacFactory : IGUIFactory
{
    public IButton CreateButton() => new MacButton();
    public ICheckbox CreateCheckbox() => new MacCheckbox();
}

Step 3: Abstract Product: Interfaces for buttons and checkboxes.

public interface IButton
{
    void Paint();
}

public interface ICheckbox
{
    void Paint();
}

Step 4: Concrete Product: Implementations for Windows and macOS.

public class WinButton : IButton
{
    public void Paint()
    {
        Console.WriteLine("Rendering a button in a Windows style.");
    }
}

public class MacButton : IButton
{
    public void Paint()
    {
        Console.WriteLine("Rendering a button in a macOS style.");
    }
}

public class WinCheckbox : ICheckbox
{
    public void Paint()
    {
        Console.WriteLine("Rendering a checkbox in a Windows style.");
    }
}

public class MacCheckbox : ICheckbox
{
    public void Paint()
    {
        Console.WriteLine("Rendering a checkbox in a macOS style.");
    }
}

Step 5: Client: Uses the abstract factory to create and use GUI components.

public class Application
{
    private readonly IGUIFactory _factory;
    private IButton _button;
    private ICheckbox _checkbox;

    public Application(IGUIFactory factory)
    {
        _factory = factory;
    }

    public void CreateUI()
    {
        _button = _factory.CreateButton();
        _checkbox = _factory.CreateCheckbox();
    }

    public void Paint()
    {
        _button.Paint();
        _checkbox.Paint();
    }
}

Step 6: Example Usage

public class Program
{
    public static void Main(string[] args)
    {
        IGUIFactory factory;
        if (Environment.OSVersion.Platform == PlatformID.Win32NT)
        {
            factory = new WinFactory();
        }
        else
        {
            factory = new MacFactory();
        }

        var app = new Application(factory);
        app.CreateUI();
        app.Paint();
    }
}