Template Method Design Pattern (C#)
Вставка
- Опубліковано 25 тра 2021
- Template Method design pattern explained with examples in code. Substitute parts of your algorithm using inheritance.
Patreon 🤝 / raw_coding
Courses 📚 learning.raw-coding.dev
Shop 🛒 shop.raw-coding.dev
Discord 💬 / discord
Twitter 📣 / anton_t0shik
Twitch 🎥 / raw_coding
Playlist: • c# design patterns
Source: github.com/raw-coding-youtube...
#csharp #templatemethod #designpatterns
your use cases is very self-explanatory, easy to understand, thanks for sharing 🙏
Always good to learn something from you. Keep coding!
Thank you)
Loving that poster!
Cheers
What do you advice to do if step1 step2 and step3 need information from database
inject the database in to the base class
Great pattern, a bit underrated, but I found myself using it more and more lately. Especially when I have more than 1 implementation on the same interface. By using template pattern , I enforce a certain high-level behavior and execution sequence, but let subclasses specify the details of every step. Good explanation though.
Cheers, yeah it is quite a useful one )
👍🏽
)
Please, update source on github.
done! thank you for letting me know, also nice to know someone is actually looking at it! :D
why not just events?
How would you replace a template method patter with events lad?
@@RawCoding
i was thinking something like this
public class Process {
private Action OnStartEvent;
public Process(){
OnStartEvent += A;
OnStartEvent += B;
OnStartEvent += C;
OnStartEvent += D;
}
public void Start(int a){
OnStartEvent.Invoke(a);
}
public void A(int a){}
public void B(int a){}
public void C(int a){
if(a == 0) return;
}
public void D(int a){
if(a != 0) return;
}
}
but instead of making A,B,C,D virtual or abstract, we could make the constructor receive functions and add to the event dynamically, so we don't need to create a new class everytime to create a new different process, so we now can follow the open and closed principle from solid.
Events don’t have access to Process internals, not the same thing, you’re thinking strategy/observer pattern.
You’ll still be defining classes for them externally.
And we’re following ocp ether way.
@@RawCoding i see now, i have just watched your strategy design pattern, it makes more sense now, what I was trying to do was much more close to the strategy pattern than the template method, I understand now, thank you.