Skip to content

Instantly share code, notes, and snippets.

@perrytribolet
Last active September 12, 2018 14:59
Show Gist options
  • Save perrytribolet/aca7cb333b5027fcc0930b06931e2711 to your computer and use it in GitHub Desktop.
Save perrytribolet/aca7cb333b5027fcc0930b06931e2711 to your computer and use it in GitHub Desktop.
Sample Code for the Recipe Pattern
using System;
using RecipeStandardLibrary;
namespace ConsoleApp
{
class Program
{
static RefWrapper<string> stringWrapper = new RefWrapper<string>();
static StringRecipeComposite recipe =
new StringRecipeComposite(new RefWrapper<string> { Value = "Hello World" });
static void Main(string[] args)
{
recipe.ProductWrapper.Value = "Hello World!";
Console.WriteLine(Recipe<string>.FinishedProduct(recipe));
}
}
}
using System;
namespace RecipeStandardLibrary
{
public abstract class Recipe<T>
{
public RefWrapper<T> ProductWrapper { set; get; }
public static T FinishedProduct(Recipe<T> recipe)
{
recipe.Execute();
return recipe.ProductWrapper.Value;
}
public Recipe(RefWrapper<T> productWrapper)
{
ProductWrapper = productWrapper;
}
public abstract void Execute();
}
}
using System;
using System.Collections.Generic;
namespace RecipeStandardLibrary
{
public abstract class RecipeComposite<T> : Recipe<T>
{
public List<Recipe<T>> Recipes { get; set; } = new List<Recipe<T>>();
public RecipeComposite(RefWrapper<T> productWrapper):base( productWrapper)
{
}
public override void Execute()
{
foreach (var recipe in Recipes) recipe.Execute();
}
}
}
using System;
namespace RecipeStandardLibrary
{
public class RefWrapper<T>
{
public RefWrapper()
{
}
public T Value
{
get;
set;
}
}
}
using System;
namespace RecipeStandardLibrary
{
public abstract class StringRecipe : Recipe<string>
{
public StringRecipe(RefWrapper<string> productWrapper):
base(productWrapper)
{
}
public override void Execute()
{
this.ProductWrapper.Value += $"+{this.GetType().Name}";
}
}
}
using System;
namespace RecipeStandardLibrary
{
public class StringRecipe1: StringRecipe
{
public StringRecipe1(RefWrapper<string> productWrapper): base(productWrapper)
{
}
}
}
using System;
namespace RecipeStandardLibrary
{
public class StringRecipe2 : StringRecipe
{
public StringRecipe2(RefWrapper<string> productWrapper): base(productWrapper)
{
}
}
}
using System;
using System.Collections.Generic;
namespace RecipeStandardLibrary
{
public class StringRecipeComposite : RecipeComposite<string>
{
public StringRecipeComposite(RefWrapper<string> productWrapper) : base(productWrapper)
{
this.Recipes = new List<Recipe<string>>{
new StringRecipe1(this.ProductWrapper),
new StringRecipe2(this.ProductWrapper)
};
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment