Template method design pattern more useful after observer, visitor, command, factory, decorator , single tone and of course facade and adapter :-))), but anyway I think it very nice and not so simple to understand.
Those two reasons, why I would like show this pattern in VERY simple way, I hope it will helps understand this pattern in couple of minutes:
OK, first of all short explanation:
Suppose, we want to prepare for us and tea for friend. We will boil water and after put coffee and tea into the cups. So, we will perform 4 actions:
1. - boil water and put into the cup_1
2. - boil water and put into the cup_2
3. - put coffee into the cup_1
4. - put tea into the cup_2
We have 4 methods and 2 same actions at all (1&2)
So, we can create template method for 1 & 2.
OK, Lets see some code in order to understand it simple:
Those two reasons, why I would like show this pattern in VERY simple way, I hope it will helps understand this pattern in couple of minutes:
OK, first of all short explanation:
Suppose, we want to prepare for us and tea for friend. We will boil water and after put coffee and tea into the cups. So, we will perform 4 actions:
1. - boil water and put into the cup_1
2. - boil water and put into the cup_2
3. - put coffee into the cup_1
4. - put tea into the cup_2
We have 4 methods and 2 same actions at all (1&2)
So, we can create template method for 1 & 2.
OK, Lets see some code in order to understand it simple:
using System; namespace TemplateMethodPattern { class Program { static void Main(string[] args) { var tea = new Tea(); tea.Create(); var cofee = new Cofee(); cofee.Create(); Console.ReadLine(); } } public abstract class TemplateCreateDrink { public void Create() { BoilWater(); AddSomethink(); } public void BoilWater() { Console.WriteLine("Boil Water"); } public abstract void AddSomethink(); } public class Tea: TemplateCreateDrink { public override void AddSomethink() { Console.WriteLine("Add Tea to Water"); } } public class Cofee : TemplateCreateDrink { public override void AddSomethink() { Console.WriteLine("Add Cofee to Water"); } } }
And...we create template pattern in order to prepare tea and coffee :)