Skip to content

Instantly share code, notes, and snippets.

@marcusholmgren
Last active November 6, 2024 06:26
Show Gist options
  • Save marcusholmgren/4167077 to your computer and use it in GitHub Desktop.
Save marcusholmgren/4167077 to your computer and use it in GitHub Desktop.
Ayende's modern version of the AbstractFactory
/*
* thanks to Ayende for idea, http://tekpub.com/shows/mct/1
*/
using System;
namespace AbstactFactory;
class Program
{
public static void Main()
{
Setup();
var factory = new Factory();
string greeting = factory.Create();
Console.WriteLine($"AbstractFactory say's {greeting}");
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
static void Setup()
{
Console.Write("Choose 1 or 2? ");
var input = Console.ReadLine();
if (input.Contains("1"))
Factory.FactoryCreated += factory => factory.Create = () => "Hello World!";
else if (input.Contains("2"))
Factory.FactoryCreated += factory => factory.Create = () => "Hejsan";
else
Factory.FactoryCreated += factory => factory.Create = () => "you wrote: " + input;
}
}
/// <summary>
/// A factory class that provides a greeting string.
/// </summary>
public sealed class Factory
{
/// <summary>
/// An event that is raised when a new factory is created.
/// </summary>
public static event Action<Factory> FactoryCreated;
/// <summary>
/// Initializes a new instance of the <see cref="Factory"/> class.
/// </summary>
/// <exception cref="ArgumentException">Thrown when no configuration exists for creation.</exception>
public Factory()
{
if (FactoryCreated == null)
throw new ArgumentException("No configuration exist for creation.");
FactoryCreated(this);
}
/// <summary>
/// Gets or sets a function that creates a greeting string.
/// </summary>
public Func<string> Create { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment