Abstract Factory Pattern Example


class Program
{
    static void Main(string[] args)
    {
        /*Getting the system operating system version.*/
        var isWindows = Environment.OSVersion.VersionString.Contains("Windows");
 
        /*Creating a Gui factory that will create appropriate definitions 
            per operating system.*/
        IGuiFactory factory = 
            isWindows ? (IGuiFactory)new WindowsFactory() : (IGuiFactory)new MacFactory();
 
        /*then running the application. Each object will resolve per 
            itselves how to render or do anything.*/
        var app = new Application(factory);
        app.Run();
    }
}
 
/*Factory object consumer.*/
internal class Application
{
    private readonly IGuiFactory _factory;
 
    public Application(IGuiFactory factory)
    {
        _factory = factory;
    }
 
    public void Run()
    {
        IButton button = _factory.CreateButton();
        button.Paint();
    }
}
 
/*definition of factory interface.*/
internal interface IGuiFactory
{
    IButton CreateButton();
}
 
/*Os specific factories*/
internal class WindowsFactory : IGuiFactory
{
    public IButton CreateButton()
    {
        return new WindowsButton();
    }
}
 
internal class MacFactory : IGuiFactory
{
    public IButton CreateButton()
    {
        return new MacButton();
    }
}
 
/*Definition of button.*/
internal interface IButton
{
    void Paint();
}
 
/*base behaviours for buttons... One valid example could be Click event.*/
internal abstract class ButtonBase : IButton
{
    private readonly string _message;
 
    protected ButtonBase(string message)
    {
        _message = message;
    }
 
    public void Paint()
    {
        Console.WriteLine(_message);
    }
}
 
/*Os specific implementations.*/
internal class WindowsButton : ButtonBase
{
    public WindowsButton() : base("I am a Pc/Windows button") { }
}
 
internal class MacButton : ButtonBase
{
    public MacButton() : base("Hello I am a Mac button") { }
}

Comments