Template method pattern
public abstract class Prepare
{
public abstract void PrepareRecipe();
}
public abstract class CaffeineBeverage : Prepare
{
public sealed override void PrepareRecipe()
{
BoilWater();
Brew();
PourInCup();
if(CustomerWantsCondiments())
AddCondiments();
}
public abstract void Brew();
public abstract void AddCondiments();
public void BoilWater() { Console.WriteLine("Boiling water"); }
public void PourInCup() { Console.WriteLine("Pouring into cup"); }
public virtual bool CustomerWantsCondiments() { /*Hook*/ return true; }
}
public class Espresso : CaffeineBeverage
{
public override void Brew() { Console.WriteLine("Dripping Coffee through filter"); }
public override void AddCondiments() { Console.WriteLine("Adding Sugar and Milk"); }
public override bool CustomerWantsCondiments()
{
string input = GetInput();
try
{
if (input == "yes") return true;
else if (input == "no") return false;
else throw new ArgumentException();
}
catch (ArgumentException)
{
Console.WriteLine("Invalid input");
return CustomerWantsCondiments();
}
}
private string GetInput()
{
Console.WriteLine("Do you want milk and sugar with your espresso?");
Console.WriteLine("Enter yes or no");
string input;
try
{
var s = Console.ReadLine();
if (s != "yes" && s != "no")
throw new ArgumentException();
else input = s;
}
catch (ArgumentException)
{
Console.WriteLine("Invalid input");
return GetInput();
}
return input;
}
}
public class HouseBlend : CaffeineBeverage
{
public override void Brew() { Console.WriteLine("Stirring beans"); }
public override void AddCondiments() { Console.WriteLine("Adding kakao syrup"); }
}
public class Test
{
public static void Main(string[] args)
{
var beverage = new Espresso();
Console.WriteLine("Preparing Espresso...");
beverage.PrepareRecipe();
}
}
'코딩 공부 > 디자인패턴' 카테고리의 다른 글
프록시 패턴 (1) | 2024.12.09 |
---|---|
반복자 패턴, 컴포지트 패턴 (0) | 2024.12.05 |
어댑터 패턴, 퍼사드 패턴 (1) | 2024.12.04 |
커맨드 패턴 (0) | 2024.12.04 |
팩토리 패턴 (0) | 2024.12.03 |