IConfiguration vs IOptions NET
Synchronous and Asynchronous in .NET Core
Model Binding and Validation in ASP.NET Core
ControllerBase vs Controller in ASP.NET Core
ConfigureServices and Configure methods
IHostedService interface in .NET Core
ASP.NET Core request processing
| Observer-Pattern :👈 | 👉:Curiously-Recurring-Template-Pattern |
Template Method Pattern in C# |
The Template Method Pattern is a behavioral design pattern that defines the skeleton of an algorithm in a base class but lets subclasses override specific steps without changing the overall structure.
In the context of MVVM (Model-View-ViewModel), this pattern is often used to define a lifecycle for ViewModels: initialization, loading data, binding state, and cleanup. The base ViewModel provides the template, while derived ViewModels customize the steps.
InitializeLifecycle) and provides default implementations.LoadData, BindState) to provide custom behavior.using System;
public abstract class BaseViewModel
{
// Template Method - defines lifecycle
public void InitializeLifecycle()
{
OnCreate();
LoadData();
BindState();
OnDestroy();
}
// Steps with default or abstract behavior
protected virtual void OnCreate()
{
Console.WriteLine("BaseViewModel: OnCreate");
}
protected abstract void LoadData();
protected virtual void BindState()
{
Console.WriteLine("BaseViewModel: BindState");
}
protected virtual void OnDestroy()
{
Console.WriteLine("BaseViewModel: OnDestroy");
}
}
// Concrete ViewModel
public class UserViewModel : BaseViewModel
{
protected override void LoadData()
{
Console.WriteLine("UserViewModel: Loading user data...");
}
protected override void BindState()
{
Console.WriteLine("UserViewModel: Binding user state to UI...");
}
}
public class ProductViewModel : BaseViewModel
{
protected override void LoadData()
{
Console.WriteLine("ProductViewModel: Loading product catalog...");
}
protected override void BindState()
{
Console.WriteLine("ProductViewModel: Binding product state to UI...");
}
}
// Client
class Program
{
static void Main(string[] args)
{
BaseViewModel userVM = new UserViewModel();
userVM.InitializeLifecycle();
Console.WriteLine();
BaseViewModel productVM = new ProductViewModel();
productVM.InitializeLifecycle();
}
}
BaseViewModel: OnCreate UserViewModel: Loading user data... UserViewModel: Binding user state to UI... BaseViewModel: OnDestroy BaseViewModel: OnCreate ProductViewModel: Loading product catalog... ProductViewModel: Binding product state to UI... BaseViewModel: OnDestroy
for .NET MAUI , this pattern is highly relevant:
BaseViewModel often defines lifecycle hooks (OnAppearing, OnDisappearing, InitializeAsync).INotifyPropertyChanged for UI updates.| Observer-Pattern :👈 | 👉:Curiously-Recurring-Template-Pattern |