Last active
November 6, 2024 06:26
-
-
Save marcusholmgren/4167077 to your computer and use it in GitHub Desktop.
Ayende's modern version of the AbstractFactory
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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